Answer the question
In order to leave comments, you need to log in
How to get data with has_many through connection?
Models available
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
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
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question