I have several records with several attributes (A, B, C, D).
我有几个记录有几个属性(A,B,C,D)。
I want to be able to find which record has the higher value for a given attribute, such as D.
我希望能够找到哪个记录对于给定属性具有更高的值,例如D.
How do I do that?
我怎么做?
2 个解决方案
#1
19
You might give max_by a look.
你可以看看max_by。
objects = [some array of objects]
object_with_highest_value = objects.max_by {|obj| obj.desired_value }
#2
2
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
#1
19
You might give max_by a look.
你可以看看max_by。
objects = [some array of objects]
object_with_highest_value = objects.max_by {|obj| obj.desired_value }
#2
2
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