給定的Rails 3應用程序有如下型號:每一個新的資產創造了時間Rails 3中ActiveRecord的查詢
# == 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
資產#版本會增加,如果具有相同名稱的資產存在,所以這是什麼我的資產通常看起來像(簡體):
| 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 |
現在我需要獲取單個訂單的所有singlepage_pdfs,但僅限於每個名字的最後一個版本。我怎樣才能做到這一點?
o = Order.find(1)
singlepage_pdfs = o.singlepage_pdfs.find(...)
結果應該只包含包含資產ID 3,4 ...
感謝您前面回答。我收到了這個錯誤:''column'asset_id'必須出現在GROUP_BY子句中。也許值得一提的是我使用PostgreSQL ... – 2011-05-24 12:15:10