How to join mutli-role, multi organisation tables in Rails

大憨熊 提交于 2019-12-01 00:25:38

I think you're overcomplicating things here. The way I see it, you need a single table called memberships that should act as a join table between User, Org and Role

class Membership
  belongs_to :user
  belongs_to :org
  belongs_to :role


class User
  has_many :memberships
  has_many :orgs, through: :memberships
  has_many :roles, through: :memberships

To create a new role for a user within an organization, just do:

org = Org.create({:fullname => 'Test Org 1'})
role = Role.where('name'=>'administrator').first
membership = user.memberships.create(org_id: org.id, role_id: role.id)

To query for the roles within an organization, you can do:

org = Org.where(name: "Test Org").first
my_roles = Role.find(user.memberships.where(org_id: org.id).map(&:role_id))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!