问题
I have the following models:
#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
This looks even worse in the view, like this:
= @equipment.odometers.current_reading(@equipment)
I am thinking there should be a way better way to do this, but I can't seem to come up with or find anything. I am honestly not even sure how to search for something like this.
Thanks for any help.
回答1:
If you want the mileage for the last inserted odometer of an equipment you do
# 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
If you want to take the max odometer mileage for an equipment:
@equipment.odometers.maximum(:mileage)
Because of the Equipment has_many :odometers
relation, in the above code the :equipment_id => equipment.id
condition is implicit.
You may want to implement something similar to a counter cache, only that insted of taking the count you take the max, to speed up queries.
回答2:
You can put this in your equipment model
class Equipment < ActiveRecord::Base
belongs_to :odometer_type
has_many :odometers
def max_milage
odometers.max(:mileage)
end
end
Then you can access it like @equipment.max_milage
来源:https://stackoverflow.com/questions/8567175/correct-way-to-find-max-value-with-association-rails