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?
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
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:
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
* 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.
@parent.children.order("value DESC").first
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With