我有以下型号:找到与关联最大值正确的方法轨
#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)
我想应该有一个更好的方式来做到这一点,但我似乎无法想出或找到任何东西。我真的不知道如何搜索这样的东西。
感谢您的任何帮助。
查找列的最大值Rails的方法现在被称为[最大](HTTP访问:/ /api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-maximum)。 –