Reputation: 2411
I have a fairly simple problem in Ruby on Rails. I have three models: States, Cities & Stadiums
State has_many cities
City belongs_to State
City has_many Stadiums
Stadium belongs_to City
Stadium has a city_id
column. City has a state_id
column. Stadium does not have a state_id
column. I can access state from stadium by stadium.city.state
I would like to perform a group count to count how many Stadiums there are in a State, similar to the below:
Stadium.group(:city).count
which works fine. In other words, I want to do something like this
Stadium.group(:state).count
, which doesn't work. Is it possible? How can I do that?
Upvotes: 0
Views: 83
Reputation: 36860
I don't believe it's possible in vanilla rails. You might be able to do it with a crafted SQL statement.
Alternatively, you can use the array method but may not be as performant...
Stadium.all.group_by(&:state).count
Upvotes: 1