Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 显示和计算关联的关联_Ruby On Rails_Ruby_Devise_Associations_Relationship - Fatal编程技术网

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也是正确的,但这里的答案更好,因为它没有违反德米特定律: