简体   繁体   English

Rails 3模型继承

[英]Rails 3 Model Inheritance

I have three models: Users, which belongs to Concerts, which belongs to Regions. 我有三种模型:用户,属于Concerts,属于Regions。 A User listening to a Concert in a Region. 某地区正在听音乐会的用户。 Model belongs_to relationships set up respectively. 分别建立模型belongs_to关系。

In the Concerts controller, I count the number of Users listening to a Concert like this: 在Concerts控制器中,我计算这样收听Concert的用户数:

@listeners = @concert.users.count

However, I want to list the number of listeners per concert at the region level. 但是,我想列出区域级别每场音乐会的听众人数。 In my Region controller I want to do something like this: 在我的Region控制器中,我想执行以下操作:

@all_listeners = @region.concert.users.count . @all_listeners = @region.concert.users.count The number of listeners of each concert, in each region. 每个地区的每个音乐会的听众人数。 I know this code is not correct but that is the general idea. 我知道这段代码是不正确的,但这是一般的想法。 Any point in the right direction appreciated. 朝正确方向的任何观点表示赞赏。

Add a has_many :through to your Region class. has_many :through添加到您的Region类。

class User < ActiveRecord::Base
  belongs_to :concert
end

class Concert < ActiveRecord::Base
  belongs_to :region
  has_many :users
end

class Region < ActiveRecord::Base
  has_many :concerts
  has_many :users, :through => :concerts
end

Then you can count the users in a region as so: 然后,您可以按以下方式计算区域中的用户:

@all_listeners = @region.users.count

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

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