@brikstar

Как достать данные при связи has_many through?

Имеются модели
class Category < ActiveRecord::Base
  has_many :products
end

class Product < ActiveRecord::Base
  belongs_to :category
  has_many :product_storages
  has_many :storages, through: :product_storages
end

class Storage < ActiveRecord::Base
  has_many :product_storages
  has_many :products, through: :product_storages
end

class ProductStorage < ActiveRecord::Base
  belongs_to :product
  belongs_to :storage
end

В связующей таблице данные storage_id, product_id, amount, т.е. количество товара на каждом складе, при чем один и тот же товар может находиться на разных складах.

Вопрос в следующем, как правильно получить такие данные не прибегая к find_by_sql, т.е. средствами ActiveRecord основанных на связях?
Может /надо что-то еще проделать с моделями или я что-то не так понимаю, или буду рад информации где почитать с примерами про сложные связи между таблицами в RoR ?

select products.id, products.name,product_storages.amount,product_storages.storage_id  from products 
inner join product_storages on product_storages.product_id = products.id 
inner join categories on categories.id = products.category_id 
where product_storages.storage_id=1 and amount >0 and categories.id =1


select products.id, products.name, product_storages.amount,product_storages.storage_id  from products 
inner join product_storages on product_storages.product_id = products.id 
where product_storages.storage_id = 1 and amount >0


select products.id, products.name,SUM( product_storages.amount),product_storages.storage_id  from products 
inner join product_storages on product_storages.product_id = products.id 
where product_storages.storage_id <>1 and amount >0 
group by products.id
  • Вопрос задан
  • 2504 просмотра
Пригласить эксперта
Ответы на вопрос 1
@vsuhachev
Product.joins(:product_storages, :categories).with_nonzero_amount.where(
  product_storages: { storage_id: 1 }, categories: { id: 1}
)


И определить скоп with_nonzero_amount в классе Product
scope :with_nonzero_amount, -> where('amount > 0') }
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы