Rails has_many:通过自定义列

时间:2012-03-08 14:12:06

标签: ruby-on-rails has-and-belongs-to-many has-many

我有2个与模块ProjectsUsersRole关联的模型:

用户可以加入多个项目,项目拥有大量用户,用户可以通过“admin”或“member”角色加入项目:

class User < ActiveRecord::Base
  has_many :projects_users_role
  has_many :projects, :through => :projects_users_role
end

class Project < ActiveRecord::Base
  has_many :projects_users_role
  has_many :users, :through => :projects_users_role
end

class ProjectsUsersRole < ActiveRecord::Base
  belongs_to  :user
  belongs_to  :project

  attr_accessible :role, :user, :project
end

我可以获得当前用户的项目:

@projects = current_user.projects

但是如何让项目中的所有用户都有角色?

1 个答案:

答案 0 :(得分:0)

@projects.each do |project|
   project.projects_users_role.each do |r|
        debug r.role
   end
end