我有以下型號:找到與關聯最大值正確的方法軌
#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)。 –