Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 841
justinxreese Avatar asked Feb 20 '11 21:02

justinxreese


People also ask

How to find the maximum and minimum value of a field?

Given a list of custom objects, find the maximum and minimum value of a field among custom objects using stream in Java. 1. Using Stream.max()method

How do I find all children of a specific object?

All children of a specific object can be obtained via object.children (). This article concerns itself with only finding objects by certain criteria. Usually it is possible to search for objects by some of their properties. Here is an example that uses real names instead of symbolic names to be a bit simpler:

How to find the maximum and minimum object in a stream?

The idea is to convert the list of objects into a stream of objects and then use the Stream#max()method that accepts a Comparatorto compare objects based on a field value and returns an Optionalcontaining the maximum object in the stream. Similarly, we can use the Stream#min()method to find the minimum object in the stream. 1 2 3

What is the return value when passing a child object?

* When passing a child only the children of that child * are searched. * * The return value is an array with the found object * at index 0, and all its parents (if any), starting * with the closest parent.


1 Answers

@parent.children.order("value DESC").first 
like image 162
fl00r Avatar answered Oct 02 '22 15:10

fl00r