【发布时间】:2012-08-22 16:58:47
【问题描述】:
我目前正在尝试在模型上创建自定义方法,其中使用的条件是 has_many 关联的条件。我目前的方法是:
class Dealer < ActiveRecord::Base
has_many :purchases
def inventory
inventory = Vehicle.where(:purchases => self.purchases)
return inventory
end
end
这不起作用,因为 Vehicle has_many :purchases (因此车辆型号上没有“购买”列)。如何在此类查询中使用 vehicle.purchases 数组作为条件?
更复杂的是,has_many 也是多态的,所以我不能简单地在查询中使用 .join(:purchases) 元素,因为没有 VehiclePurchase 模型。
编辑:为清楚起见,我购买的车型和车型的相关部分如下:
class Purchase < ActiveRecord::Base
attr_accessible :dealer_id, :purchase_type_id
belongs_to :purchase_item_type, :polymorphic => true
end
class Vehicle < ActiveRecord::Base
has_many :purchases, :as => :purchase_item_type
end
【问题讨论】:
-
请添加您提到的多态关联。
-
我已经添加了显示关联的相关模型。
标签: ruby-on-rails activerecord