Ruby on rails 显示和计算关联的关联
我想计算属于项目团队的用户数量。这些协会如下:Ruby on rails 显示和计算关联的关联,ruby-on-rails,ruby,devise,associations,relationship,Ruby On Rails,Ruby,Devise,Associations,Relationship,我想计算属于项目团队的用户数量。这些协会如下: 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> 我收到
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>
我收到的错误是:未定义的方法“users”
。我也在使用Desive
project_controller.rb中是否需要一个方法才能工作?当您执行
@project.teams
时,它将返回一个数组作为团队列表,因为一个项目有许多团队,所以要找出该项目中第一个团队的用户数,您可以执行以下操作
@project.teams.first.users.count
或者你需要找到你想要的团队,然后做
.users。数一数
因为,不清楚你到底想要什么,这是我对答案的最佳猜测
您可以将新关联添加到模型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
类用户
属于:团队
结束
班队
属于:项目
有很多:用户
结束
班级项目
有很多队吗
has-many:users,through::teams#在Project
中添加一个关联has-many:users,through::teams
,然后使用@Project。users
@kiddorails是正确的,Subash也是正确的,但这里的答案更好,因为它没有违反德米特定律: