【问题标题】:Show and count association of association显示和统计协会的协会
【发布时间】:2018-07-18 06:53:33
【问题描述】:

我想计算属于某个项目的团队的用户数。关联如下:

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 中的方法才能使其工作?

【问题讨论】:

标签: ruby-on-rails ruby devise associations relationship


【解决方案1】:

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

您可以将新的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

【讨论】:

    【解决方案2】:

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

    @project.teams.first.users.count
    

    或者你需要找到你想要的团队,然后在上面做.users.count

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-29
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多