vinothini
vinothini

Reputation: 2604

Group by in rails

In my table I have event and date(as columns name). Events can repeat.

I want to know the count of each event in the table.

Any suggestion?

Upvotes: 0

Views: 314

Answers (4)

Taryn East
Taryn East

Reputation: 27757

Try this:

Event.count(:group => :name)

It should return an ordered hash of event-name vs count.

Upvotes: 0

Aditya Sanghi
Aditya Sanghi

Reputation: 13433

Assuming the column in your Event model is "event". (otherwise replace "event" by whatever you want to group by

x = Event.group(:event).count

The above returns you a hash keyed on the event and the value representing the count

puts x["The Temper Trap"] # => 3 

Upvotes: 1

Simpleton
Simpleton

Reputation: 6415

You can use map:

Event.map { |event| event.count }

Or a loop:

For event in Event
  event.count
end

Or iteration:

Event.each do |event|
  event.count
end

Upvotes: 0

Ben
Ben

Reputation: 13645

Event.all.count should do it

Upvotes: 1

Related Questions