2011-12-19 77 views
1

我有以下型号:找到与关联最大值正确的方法轨

#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) 

我想应该有一个更好的方式来做到这一点,但我似乎无法想出或找到任何东西。我真的不知道如何搜索这样的东西。

感谢您的任何帮助。

回答

5

如果你想为一个设备的最后插入里程表的里程数,你做

# 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.max(:mileage) 

因为Equipment has_many :odometers的关系,在上面的代码中:equipment_id => equipment.id条件是隐含的。

你可能想要实现类似于counter cache的东西,只是为了加快查询速度而采取了最大计数。

+1

查找列的最大值Rails的方法现在被称为[最大](HTTP访问:/ /api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-maximum)。 –

1

您可以在设备模型把这个

class Equipment < ActiveRecord::Base 

    belongs_to :odometer_type 
    has_many :odometers 

    def max_milage 
    odometers.max(:mileage) 
    end 
end 

然后你就可以像@equipment.max_milage

相关问题