Q:

Show and count association of association

I would like to count the number of users that belong to a team which belongs to a project. The associations are as follows:
user belongs_to :team
team has_many :users
project has_many :teams
team belongs_to :project

In the projects/show.html.erb, I am using the following code to count the total number of users belonging to all teams which belong to a project
<h2 class="number"><%= @project.teams.users.count %></h2>

The error I am receiving is: undefined method 'users'. I am also using Devise
Is a method in project_controller.rb required for this to work?

A:

Since, it is not clear what you want exactly, this is my best guess at the answer.
You can add a new has_many :through association to model Project to get the count of all the users in a 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

