简体   繁体   English

加入has_many:通过属性

[英]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 . 我一直在寻找一种使用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. 我最好的是能够进行查询,以最低的销售价格返回灯泡(我认为),但输出中未包含price属性。

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 . 如果查询工作正常,则可以访问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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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