【问题标题】:Rails has_many :through with custom columnRails has_many:通过自定义列
【发布时间】:2012-03-08 14:12:05
【问题描述】:

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

用户可以加入多个项目,项目有很多用户,用户以“管理员”或“成员”的角色加入项目:

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

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

【问题讨论】:

  • 你的问题有点混乱。您能否详细说明您想要返回的内容以及您拥有的数据?
  • 抱歉,这仍然是不够的信息。 '如何让项目中的所有用户都有角色?这意味着什么?什么角色?什么项目?
  • 所以澄清一下,您想在 current_user 所属的所有项目中获取具有特定角色的所有用户?

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


【解决方案1】:
@projects.each do |project|
   project.projects_users_role.each do |r|
        debug r.role
   end
end

【讨论】:

    猜你喜欢
    • 2011-09-13
    • 2014-07-06
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    相关资源
    最近更新 更多