2011-12-19 24 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

相關問題