我的 Rails 4.1 应用程序中有以下模型结构:
delivery_service.rb
class DeliveryService < ActiveRecord::Base
attr_accessible :name, :description, :courier_name, :active, :country_ids
has_many :prices, class_name: 'DeliveryServicePrice', dependent: :delete_all
end
delivery_service_price.rb
class DeliveryServicePrice < ActiveRecord::Base
attr_accessible :code, :price, :description, :min_weight, :max_weight, :min_length, :max_length,
:min_thickness, :max_thickness, :active, :delivery_service_id
belongs_to :delivery_service
end
如您所见,送货服务有很多送货服务价格。我正在尝试从送货服务价格表中检索记录; 在外键的唯一范围内选择具有最低价格属性的记录,delivery_service_id(因此本质上是每个送货服务最便宜的送货服务价格)。
如何从表中选择唯一记录,外键属性作为范围?
我希望我已经对此进行了足够的解释,如果您需要更多信息,请告诉我。
谢谢
更新 #1:
我正在努力实现的示例:
delivery_service_prices 表:
id: 1, price: 2.20, delivery_service_id: 1
id: 2, price: 10.58, delivery_service_id: 1
id: 3, price: 4.88, delivery_service_id: 2
id: 4, price: 1.20, delivery_service_id: 2
id: 5, price: 14.99, delivery_service_id: 3
预期结果:
id: 1, price: 2.20, delivery_service_id: 1
id: 4, price: 1.20, delivery_service_id: 2
id: 5, price: 14.99, delivery_service_id: 3
最佳答案
由于 PostgreSQL 在遵守 SQL 标准方面更加严格(这是正确的),因此需要进行一些调整才能获得正确的结果。
以下查询针对每次送货服务返回最低送货服务价格的正确结果:
DeliveryServicePrice.select('DISTINCT ON (delivery_service_id) *').order('delivery_service_id, price ASC')
我需要在订单条件中添加delivery_service_id属性,否则PostgreSQL会抛出以下列错误:
PG::InvalidColumnReference: ERROR: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
希望这对偶然发现它的人有所帮助!
关于ruby-on-rails - 如何根据 Rails 中的外键列选择唯一记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26448520/