B
B
brikstar2014-12-25 17:00:12
Ruby on Rails
brikstar, 2014-12-25 17:00:12

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

In the link table, the storage_id, product_id, amount data, i.e. the quantity of goods in each warehouse, and the same goods can be in different warehouses.
The question is how to get such data correctly without resorting to find_by_sql, i.e. means of the ActiveRecord based on communications?
Maybe / I need to do something else with the models, or I don’t understand something, or I’ll be happy with information where to read with examples about complex relationships between tables in 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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vsuhachev, 2014-12-25
@vsuhachev

Product.joins(:product_storages, :categories).with_nonzero_amount.where(
  product_storages: { storage_id: 1 }, categories: { id: 1}
)

And define scope with_nonzero_amount in Product class
scope :with_nonzero_amount, -> where('amount > 0') }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question