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

谁都会走 提交于 2019-12-14 00:16:20

问题


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

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

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?


回答1:


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



回答2:


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)



回答3:


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

@parent.children.max_by(&:value)



回答4:


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


来源:https://stackoverflow.com/questions/5060280/find-activerecord-object-by-maximum-field-value-of-a-child-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!