user2618465
user2618465

Reputation: 87

Rails query to get highest amount

I have this function:

     Order.find_by_amount().amount

I am stuck at what to insert in () to get highest amount.

Upvotes: 0

Views: 49

Answers (4)

Muhamamd Awais
Muhamamd Awais

Reputation: 2385

I don't think there would be any problem if you google it first. Please do search first.

Here 3 possible ways to do it

# default sorting order is ascending order 
Order.order(:amount).last.amount

# order the amount in descending order
Order.order('amount DESC').first.amount

# Calculates the maximum value on a given column. 
Order.maximum(:amount)

Upvotes: 0

Sagar.Patil
Sagar.Patil

Reputation: 991

To get highest amount you can use aggregate functions:

eg: Order.maximum(:amount)

Upvotes: 1

Debadatt
Debadatt

Reputation: 6015

If amount is a field in orders table then you can get the highest amount order by this

Order.order('amount DESC').first.amount

Upvotes: 0

CupraR_On_Rails
CupraR_On_Rails

Reputation: 2489

Don't use find_by methods. You can do this with:

Order.order(:amount).last.amount #the second order is to sort in your database

I hope it helps

Upvotes: 0

Related Questions