Ninja Boy
Ninja Boy

Reputation: 1170

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.

Upvotes: 4

Views: 5938

Answers (2)

C dot StrifeVII
C dot StrifeVII

Reputation: 1885

try doing this

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

or you could try this

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

or

# 1
Record.where(category: :animal).order(value: :desc).first

# 2
Record.where(category: :animal).order(:value).last

Upvotes: 7

Junan Chakma
Junan Chakma

Reputation: 651

YourModelName.order("frequency DESC").first

Upvotes: 3

Related Questions