用于分隔多态关系的范围

时间:2016-04-08 10:27:11

标签: ruby-on-rails ruby-on-rails-4 activerecord rails-activerecord

我在Rails 4项目中有以下数据库关系

class Hat < ActiveRecord::Base
  belongs_to :sale, as: product
end

class Shoe < ActiveRecord::Base
  belongs_to :sale, as: product
end

class Sale < ActiveRecord::Base
  has_many :products, polymorphic: true

  scope :hats, -> { ??? }
  scope :shoes, -> { ??? }
end

鉴于@sale对象,我如何获得属于特定模型的所有产品,例如HatShoe

1 个答案:

答案 0 :(得分:1)

您的表格中应该有product_type(有关详情,请参阅the guides),因此我会对此进行查询:

scope :hats, -> { where(product_type: Hat.name) }
# Not sure that this `Hat.class.name` is the actual value in the table, 
# so you might aswell check in your DB what's the correct value.