butterywombat
butterywombat

Reputation: 2089

rails summing column values of rows with similar attributes

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 really understand the syntax of the 'where("date(purchased_at) = ?", date)' part.

Thanks for helping a rails newbie!

Upvotes: 2

Views: 660

Answers (1)

Andrei S
Andrei S

Reputation: 6516

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

Upvotes: 3

Related Questions