【发布时间】: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 中的方法才能使其工作?
【问题讨论】:
-
在
Project中添加关联has_many :users, through: :teams,然后使用@project.users -
@kiddorails 是正确的,Subash 也是如此,但这里的答案更好,因为它不违反 demeter 定律:rubyblog.pro/2016/09/rails-demeters-law-and-delegate
标签: ruby-on-rails ruby devise associations relationship