显示和统计协会的协会

Show and count association of association

我想统计属于某个项目的团队的用户数。协会如下:

user belongs_to :team
team has_many :users
project has_many :teams
team belongs_to :project

在projects/show.html.erb中,我使用下面的代码来计算属于一个项目的所有团队的用户总数

<h2 class="number"><%= @project.teams.users.count %></h2>

我收到的错误是:undefined method 'users'。我也在使用设计 是否需要 project_controller.rb 中的方法才能工作?

当您执行 @project.teams 时,它将 return 作为团队列表的数组,因为一个项目有很多团队,因此要找出该项目中第一个团队的用户数量可以做

@project.teams.first.users.count

或者您需要找到您想要的团队,然后.users.count

因为清楚你到底想要什么,这是我对答案的最佳猜测

您可以将新的 has_many :through 关联添加到模型 Project 以获取项目中所有用户的计数。

class User
  belongs_to :team
end

class Team
  belongs_to :project
  has_many :users
end

class Project
  has_many :teams
  has_many :users, through: :teams   # <--- New association
end

project = Project.find(<project_id>)

# Get the count of all users in a project
project.users.count

# Get the count of users in a team
team = project.teams.find(<team_id>)   # Or `Team.find(<team_id>)`
team.users.count