开发者

rails summing column values of rows with similar attributes

开发者 https://www.devze.com 2023-02-03 18:28 出处:网络
I have a Sites table that has columns name, and time. The name does not have to be unique. So for example I may have the entries \'hi.com, 5\', \'hi.com, 10\', \'bye.com, 4\'.

I have a Sites table that has columns name, and time. The name does not have to be unique. So for example I may have the entries 'hi.com, 5', 'hi.com, 10', 'bye.com, 4'. I would like to sum up all the unique sites so that i get 'hi.com, 15' and 'bye.com, 4' for plotting purposes. How can I do that? (For some reference I was looking at http://railscasts.com/episodes/223-charts but I couldn't get the following (translated to my table) to work

def self.total_on(date) 
  where("date(purchased_at) = ?", date).sum(:total_price) 
end

nor do I 开发者_StackOverflow中文版really understand the syntax of the 'where("date(purchased_at) = ?", date)' part.

Thanks for helping a rails newbie!


let's say you have a model called Site, with columns name and time

to do what you want, just say something like

sites = Site.sum(:time, :group => 'name')

this will result a hash like

{"bye.com"=>4, "hi.com"=>15}

then, you can do whatever you want with the hash

0

精彩评论

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