【问题标题】:correct way to find max value with association rails使用关联导轨找到最大值的正确方法
【发布时间】:2023-04-05 08:37:02
【问题描述】:

我有以下型号:

#equipment.rb
class Equipment < ActiveRecord::Base
  belongs_to :odometer_type
  has_many :odometers
end

#odometer.rb
class Odometer < ActiveRecord::Base
  belongs_to :equipment

  # I am currently doing this to find the last mileage entered (which is wrong too cause I want the mileage from the max date entered)

  def self.current_reading(equipment)
    all.where(:equipment_id => equipment.id).max(:mileage)
  end  
end

这在视图中看起来更糟,像这样:

= @equipment.odometers.current_reading(@equipment)

我认为应该有更好的方法来做到这一点,但我似乎无法想出或找到任何东西。老实说,我什至不知道如何搜索这样的东西。

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.1 associations max


    【解决方案1】:

    如果你想要你做的设备最后插入的里程表的里程数

    # assuming autoincrement id
    @equipment.odometers.order('odometers.id DESC').limit(1).first.mileage
    
    # assuming created_at column
    @equipment.odometers.order('odometers.created_at DESC').limit(1).first.mileage
    

    如果您想获取设备的最大里程表里程:

    @equipment.odometers.maximum(:mileage)
    

    由于Equipment has_many :odometers 关系,在上面的代码中:equipment_id =&gt; equipment.id 条件是隐含的。

    您可能想要实现类似于counter cache 的东西,只是为了加快查询速度。

    【讨论】:

    • Rails 查找列最大值的方法现在称为maximum
    【解决方案2】:

    你可以把它放在你的设备模型中

    class Equipment < ActiveRecord::Base
    
      belongs_to :odometer_type
      has_many :odometers
    
      def max_milage
        odometers.max(:mileage)
      end
    end
    

    然后你可以像@equipment.max_milage一样访问它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多