Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 使用关联rails查找最大值的正确方法_Ruby On Rails_Ruby On Rails 3.1_Associations_Max - Fatal编程技术网

Ruby on rails 使用关联rails查找最大值的正确方法

Ruby on rails 使用关联rails查找最大值的正确方法,ruby-on-rails,ruby-on-rails-3.1,associations,max,Ruby On Rails,Ruby On Rails 3.1,Associations,Max,我有以下型号: #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 e

我有以下型号:

#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
我在想应该有更好的方法来做到这一点,但我似乎没有想出或找到任何东西。老实说,我甚至不知道如何寻找这样的东西


感谢您的帮助。

如果您需要设备最后一次插入里程表的里程数

# 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.maximum(:mileage)
由于
设备具有多:里程表
关系,因此在上述代码中,
:device\u id=>device.id
条件是隐式的


您可能希望实现类似于a的功能,而不是计算最大值,以加快查询速度。

您可以将其放入设备模型中

class Equipment < ActiveRecord::Base

  belongs_to :odometer_type
  has_many :odometers

  def max_milage
    odometers.max(:mileage)
  end
end
class设备

然后您可以像
@equipment.max\u milage

一样访问它。现在调用Rails方法来查找列的最大值。
class Equipment < ActiveRecord::Base

  belongs_to :odometer_type
  has_many :odometers

  def max_milage
    odometers.max(:mileage)
  end
end