简体   繁体   English

如何在 Rails 中按第二个订单 belongs_to 分组?

[英]How do I group by a second order belongs_to in Rails?

I have a fairly simple problem in Ruby on Rails.我在 Rails 上的 Ruby 中有一个相当简单的问题。 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_id列。 City has a state_id column. City 有一个state_id列。 Stadium does not have a state_id column. Stadium没有state_id列。 I can access state from stadium by stadium.city.state我可以通过 Stadium.city.state 从体育场访问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:我想进行组计数以计算 State 中有多少个体育场,类似于以下内容:

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?我怎样才能做到这一点?

I don't believe it's possible in vanilla rails.我不相信这在香草铁轨中是可能的。 You might be able to do it with a crafted SQL statement.您可以使用精心制作的 SQL 语句来做到这一点。

Alternatively, you can use the array method but may not be as performant...或者,您可以使用数组方法,但性能可能不那么高......

Stadium.all.group_by(&:state).count

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM