I have what I though to be a very simple set of database models with a many-to-many type association through a linker table.
class Product < ActiveRecord::Base
has_many :store_products
has_many :stores, through: store_products
end
class StoreProduct < ActiveRecord::Base
belongs_to :store
belongs_to :product
validates :price, presence: true
end
class Store < ActiveRecord::Base
has_many :store_products
has_many :products, through: :store_product
end
So many stores can sell many products and can each sell them at different prices. I have been looking for a way to list all products along with their lowest price across all stores using joins
. I have had next to no luck with this. The best I have had was being able to make a query that returned bulbs for the lowest selling price (I think) but the price attribute was not included in the output.
The query I used to do this was:
Product.joins(:store_products).select('products.*, MIN(store_products.price) AS store_product_price')
Any suggestions on where I am going wrong or what I need to take a look at?
If your query works fine, you can access store_product_price
. To see it, just try this:
Product.joins(:store_products)
.select('products.*, MIN(store_products.price) AS store_product_price')
.each { |p| puts p.store_product_price }
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다