【发布时间】: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