正确的方法找到与关联轨最大值 [英] correct way to find max value with association rails

查看:149
本文介绍了正确的方法找到与关联轨最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

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

感谢您的帮助。

推荐答案

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

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

由于的设备的has_many:里程表的关系,在上述code中的:equipment_id =&GT; equipment.id 的条件是隐含的。

Because of the Equipment has_many :odometers relation, in the above code the :equipment_id => equipment.id condition is implicit.

您可能要实现类似计数器缓存的东西,只有insted的服用你把最大的计数,加快查询。

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.

这篇关于正确的方法找到与关联轨最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆