我目前正在尝试在模型上创建自定义方法,其中使用的条件是 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