在 rails 获得 ruby 中的较高值

get the higher value in ruby on rails

我正在与 ruby 合作 rails,我有一个问题。

我有一个 table 包含这样的数据:

{id: 471, from_city_id: '9', to_city_id: 14, product_id: 61, saving_in_from_currency: 262.0},
{id: 472, from_city_id: '9', to_city_id: 14, product_id: 61, saving_in_from_currency: 150.0}

这里是数据模型,

# == Schema Information
#
# Table name: pricings
#
#  id                      :integer          not null, primary key
#  from_city_id            :integer
#  to_city_id              :integer
#  product_id              :integer
#  saving_in_from_currency :decimal(, )
#  created_at              :datetime
#  updated_at              :datetime
#

class Pricing < ActiveRecord::Base
  belongs_to :from_city, :class_name => 'City'
  belongs_to :to_city, :class_name => 'City'
  belongs_to :product
end

我尝试在我的视图中显示 table,如下所示:

例如:

用户 select from_city_id,我为这个 id 显示了所有这样的元素

            to_city_id        to_city_id          to_city_id
product_id    price               price               price
product_id    price               price               price   
product_id    price               price               price
product_id    price               price               price

目前我select"saving_in_from_currency",由from_city_id,to_city_id和product_id。

但是就像你看到的那样,在某些情况下,只有 id 和 saving_in_from_currency 发生变化,我想像这样为每种情况显示更高的值,这里是“262.0”。

你知道我该怎么做吗?(抱歉我的英语不好)

谢谢。

看来您可能会受益于在查询中使用 distinct。我怀疑这样的事情会实现你想要的。 (当然要替换型号名称,因为上面没有提到)。

Model.select(:from_city_id, :to_city_id, :product_id).distinct.order(saving_in_from_currency: :desc)

编辑: 或者,如果您需要访问 from_city_idto_city_idproduct_id 以外的模型属性,这也可以。

# Replace with any additional constraints as needed
p = Pricing.all.order(saving_in_from_currency: :desc)
p.uniq! { |a| [a.from_city_id, a.to_city_id, a.product_id] }