Ninja Boy Ninja Boy - 1 month ago 9
Ruby Question

Select a record which has the highest value in a column in Rails

I have a column called 'frequency' in my database. I want to select the records of a particular category in which frequency is more. Like there will be 5 records of same category but each may have different frequency. Out of all these 5 records, I want the record whose value in frequency is more.

Say,

record 1 frequency value = 10

record 2 frequency value = 20

record 3 frequency value = 30

record 4 frequency value = 10

record 5 frequency value = 50

I want record 5 as my output.

Thanks.

Answer

try doing this

Record.where(category: 'animal').maximum("value")

or you could try this

Record.where(category: 'animal').order("value DESC").first
Comments