jus*_*ese 28 activerecord ruby-on-rails
如何找到与ActiveRecord计算结果相关联的对象而不是值?
例如,我有@parent有很多孩子.我想找到具有最大'价值'的孩子.
我知道我可以做@ parent.children.maximum(:value),但这会返回最大值.是否有类似于maximum和minimum的方法返回整个对象而不是值,以便我可以使用最大对象中的不同字段?
fl0*_*00r 54
@parent.children.order("value DESC").first
Run Code Online (Sandbox Code Playgroud)
Wil*_*Ayd 26
不确定这是否是最有效的,但是一旦你有了最大值,你可以在哈希中传递它以获得对象
@maxvalue = @parent.children.maximum(:value)
@myObject = @parent.children.where(:value => @maxvalue)
Run Code Online (Sandbox Code Playgroud)
通过使用ruby的#max_by,这是我个人最喜欢的可读性:
@parent.children.max_by(&:value)
Run Code Online (Sandbox Code Playgroud)
@parent.children.first(:conditions => {:value => @parent.children.maximum(:value)})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27497 次 |
| 最近记录: |