我在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
对象,我如何获得属于特定模型的所有产品,例如Hat
或Shoe
?
答案 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.