简体   繁体   English

使用关联轨道找到最大值的正确方法

[英]correct way to find max value with association rails

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. 谢谢你的帮助。

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. 由于Equipment has_many :odometers关系,在上面的代码中:equipment_id => equipment.id条件是隐含的。

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. 您可能希望实现类似于计数器缓存的功能 ,只需要计算您采用最大值的计数,以加快查询速度。

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 然后你可以像@equipment.max_milage一样访问它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM