【问题标题】:Rails - Query with has_many associationRails - 使用 has_many 关联进行查询
【发布时间】: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


【解决方案1】:
class Dealer < ActiveRecord::Base
  def inventory
    Vehicle.where(:id => purchases.where(:purchase_item_type_type => "Vehicle").map(&:purchase_item_type_id))
  end
end

或者:

  def inventory
    purchases.includes(:purchase_item_type).where(:purchase_item_type_type => "Vehicle").map(&:purchase_item_type)
  end

【讨论】:

  • 这已经存在 - 为了清楚起见,我已经更新了这个问题。我不确定这个答案有什么帮助;经销商的购买协会工作正常,问题出在车型上。
  • 通过使用has_many :vehicles, through :purchases,您可以获得与经销商购买相关的车辆。这就是我理解你想要的。
  • 抱歉,我误读了您的答案 - 这会起作用,除了购买具有关于车辆的多态 belongs_to (为清楚起见编辑问题),因此我不能添加 has_many :vehicles 到购买,因为购买不一定属于_车辆。
【解决方案2】:

我可以使用 Vehicle 模型上的 :source 和 :source_type 选项来做到这一点,这允许关联多态父项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多