【发布时间】:2011-05-24 11:44:18
【问题描述】:
给定一个具有以下模型的 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 每次创建新资产时都会增加,如果存在具有相同名称的资产,那么这就是我的资产通常的样子(简化):
|编号 |资产ID |资产类型 |姓名 |版本 |类型 | | 1 | 1 |订购 |我的.pdf | 1 |单页PDF | | 2 | 1 |订购 |我的.pdf | 2 |单页PDF | | 3 | 1 |订购 |我的.pdf | 3 |单页PDF | | 4 | 1 |订购 | bla.pdf | 1 |单页PDF |现在我需要获取单个订单的所有 singlepage_pdf,但只有每个名称的最后一个版本。我怎样才能做到这一点?
o = Order.find(1)
singlepage_pdfs = o.singlepage_pdfs.find(...)
结果应该只包含 id 为 3 和 4 的资产...
【问题讨论】:
标签: ruby-on-rails activerecord