0

я следующие соотношения БД в 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?

ответ

1

Вы должны иметь в ваших таблицах (см the guides для получения дополнительной информации) в product_type, так что я хотел бы сделать запрос по этому поводу:

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. 
+0

'' Hat.class.name' визуализирует Class' –

Смежные вопросы