gpt4 book ai didi

ruby-on-rails - Rails 3 ActiveRecord 查询

转载 作者:行者123 更新时间:2023-12-01 12:54:59 24 4
gpt4 key购买 nike

给定一个具有以下模型的 Rails 3 应用程序:

# == Schema Information
# Schema version: 20110517144920
#
# Table name: orders
#
# id :integer not null, primary key
# user_id :integer not null
# name :string(255) not null
# state :string(255)
# created_at :datetime
# updated_at :datetime
#

class Order < ActiveRecord::Base

belongs_to :user
has_many :multipage_pdfs, :as => :assetable, :dependent => :destroy
has_many :singlepage_pdfs, :as => :assetable, :dependent => :destroy
...
end


# == Schema Information
# Schema version: 20110511064747
#
# Table name: assets
#
# id :integer not null, primary key
# assetable_id :integer not null
# assetable_type :string(255) not null
# state :string(255)
# type :string(255) not null
# name :string(255) not null
# document :string(255) not null
# version :integer default(0), not null
# created_at :datetime
# updated_at :datetime
#

class Asset < ActiveRecord::Base
...
end


class SinglepagePdf < Asset
...
end

asset#version 每次创建新 Assets 时都会增加,如果存在具有相同名称的 Assets ,这就是我的 Assets 通常的样子(简化):

    | id | assetable_id | assetable_type  |   name  | version | type           |    |  1 |             1 |           Order | my.pdf  |        1 | SinglepagePdf |    |  2 |             1 |           Order | my.pdf  |        2 | SinglepagePdf |    |  3 |             1 |           Order | my.pdf  |        3 | SinglepagePdf |    |  4 |             1 |           Order | bla.pdf |        1 | SinglepagePdf |

Now i need to get all singlepage_pdfs of a single order, but only the last version for each name. How can i achieve this?

o = Order.find(1)
singlepage_pdfs = o.singlepage_pdfs.find(...)

结果应该只包含 id 为 3 和 4 的 Assets ...

最佳答案

试试这个,它按名称将所有 singlepage_pdf 分组并返回每个的最新版本

o.singlepage_pdfs.group("name").order("version DESC")

关于ruby-on-rails - Rails 3 ActiveRecord 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6109860/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com