Ruby-on-rails 通过子对象的最大字段值查找 ActiveRecord 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5060280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:28:49  来源:igfitidea点击:

Find ActiveRecord object by maximum field value of a child object?

ruby-on-railsactiverecord

提问by justinxreese

How can I find the object associated with the results of an ActiveRecord Calculation rather than a value?

如何找到与 ActiveRecord 计算的结果而不是值相关联的对象?

For example I have @parent which has many children. I would like to find the child with the maximum 'value'.

例如我有@parent,它有很多孩子。我想找到具有最大“价值”的孩子。

I understand that I can do @parent.children.maximum(:value), but this returns the maximum value. Is there a method similar to maximum and minimum that returns the entire object instead of the value so that I can use different fields from the maximum object?

我知道我可以做@parent.children.maximum(:value),但这会返回最大值。是否有类似于最大值和最小值的方法返回整个对象而不是值,以便我可以使用来自最大值对象的不同字段?

回答by fl00r

@parent.children.order("value DESC").first

回答by Will Ayd

Not sure if this is the most efficient but once you have the maximum value you can pass that along in a hash to get the object

不确定这是否是最有效的,但是一旦您拥有最大值,您就可以将其以散列形式传递以获取对象

@maxvalue = @parent.children.maximum(:value)
@myObject = @parent.children.where(:value => @maxvalue)

回答by SirLenz0rlot

This is my personal favorite when it comes to readability, by using ruby's #max_by:

在可读性方面,这是我个人最喜欢的,使用 ruby​​ 的#max_by

@parent.children.max_by(&:value)

回答by jemminger

@parent.children.first(:conditions => {:value => @parent.children.maximum(:value)})