【问题标题】:Join has_many :through attributes加入 has_many :通过属性
【发布时间】:2025-12-18 14:50:01
【问题描述】:

我拥有一组非常简单的数据库模型,通过链接器表具有多对多类型关联。

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

这么多商店可以销售多种产品,并且每个商店都可以以不同的价格出售它们。我一直在寻找一种使用joins 在所有商店中列出所有产品及其最低价格的方法。我几乎没有运气。我所拥有的最好的结果是能够查询以最低售价(我认为)返回灯泡,但输出中不包含价格属性。

我曾经这样做的查询是:

Product.joins(:store_products).select('products.*, MIN(store_products.price) AS store_product_price')

关于我哪里出错或我需要看看什么的任何建议?

【问题讨论】:

  • 你的 Product 类有 'has_many :products, through: store_products' 应该是 'has_many :Stores, through: store_products'

标签: mysql ruby ruby-on-rails-4 activerecord


【解决方案1】:

如果您的查询正常,您可以访问store_product_price。要查看它,只需尝试以下操作:

Product.joins(:store_products)
       .select('products.*, MIN(store_products.price) AS store_product_price')
       .each { |p| puts p.store_product_price }

【讨论】:

  • 我不敢相信这就是答案。谢啦。所以我试着做&lt;query&gt;.first.store_product_price。很有魅力。很高兴有一些新鲜的眼睛
最近更新 更多