简体   繁体   中英

Join has_many :through attributes

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM