0

I'm new to Ruby on Rails. I'm trying to determine the proper ruby query for the following SQL query.

Select max(bid_amount) from biddings where listing_id = 1;

I need to extract the maximum value in the bid_amount column. But it has to have a dynamic listing_id.

1 Answers1

0

Try:

Bidding.where('listing_id = :listing_id', listing_id: 1).maximum(:bid_amount)

Update:

To follow up on your comment: since you say you are passing in params[:id], it's best to convert that parameter to integer so that unwanted values don't go to the database. For e.g.

Bidding.where('listing_id = :listing_id', listing_id: params[:id].to_i).maximum(:bid_amount)
vee
  • 38,255
  • 7
  • 74
  • 78
  • It worked! I had to add params[:id] to capture correct listing_id from the route. – Rajveer Singh Tut Sep 01 '13 at 20:11
  • @RajveerSinghTut, yes you would know what to pass in. But one extra suggestion is if you're passing `params[:id]` then it's better to convert that value to integer, i.e. `params[:id].to_i` – vee Sep 01 '13 at 20:14
  • Why is it better to convert that value to an integer? – Rajveer Singh Tut Sep 01 '13 at 20:43
  • @RajveerSinghTut, in the answer I've provided you don't really need to worry about it. I'm not sure if you're aware of this already but I think it will be beneficial to read: http://guides.rubyonrails.org/security.html#sql-injection. – vee Sep 01 '13 at 21:05