开发者

Narrowing an average to a specific

开发者 https://www.devze.com 2023-02-16 07:06 出处:网络
Simple question on using averages in Rails. I\'m just trying to calculate and average for subset of bids in my table, those that apply to a single item.

Simple question on using averages in Rails. I'm just trying to calculate and average for subset of bids in my table, those that apply to a single item.

Bid.average(:amount, :conditions => ['item_id = ?', 'item_id'])
开发者_如何学运维

I can't quite figure out why this generates the following, with 'item_id', rather than the value of the item_id, which should be 5. . .

Parameters: {"id"=>"5"}
Item Load (0.1ms)  SELECT "items".* FROM "items" WHERE ("items"."id" = 5) LIMIT 1
Bid Load (0.5ms)  SELECT "bids".* FROM "bids" WHERE ("bids".item_id = 5) ORDER BY created_at DESC
Rendered bids/_bid.html.erb (6.6ms)
SQL (0.2ms)  SELECT AVG("bids"."amount") AS avg_id FROM "bids" WHERE (item_id = 'item_id')

Thanks!


Because it's what you've told to do :) You're passing a string 'item_id' as the second element of the conditions array, and it's put into the place of the question mark. If you have a variable item_id that contains the id, you don't need to put it into quotemarks:

Bid.average(:amount, :conditions => ['item_id = ?', item_id])


I think it should be this:

Bid.average(:amount, :conditions => ['item_id = ?', item_id])

item_id is getting put in there as a string, hence the quotes. Make sure to set item_id as a variable before such as:

item_id = params[:item_id] #or whatever the params are
Bid.average(:amount, :conditions => ['item_id = ?', item_id])
0

精彩评论

暂无评论...
验证码 换一张
取 消