Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the max attribute across records in ruby?

I have several records with several attributes (A, B, C, D).

I want to be able to find which record has the higher value for a given attribute, such as D.

How do I do that?

like image 647
satchel Avatar asked Oct 13 '11 04:10

satchel


2 Answers

You might give max_by a look.

objects = [some array of objects]

object_with_highest_value = objects.max_by {|obj| obj.desired_value }
like image 90
rwilliams Avatar answered Nov 17 '22 17:11

rwilliams


Depending on how many records do you have, it can be more efficient to perform the search on the DB. I would order by the desired attribute descending, and take the first record:

User.order('field DESC').first
like image 30
miguel.camba Avatar answered Nov 17 '22 16:11

miguel.camba