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

后端 未结 1 679
借酒劲吻你
借酒劲吻你 2021-01-07 00:52

I\'m trying to find a solution to a rails design that isn\'t all that obvious to me. A friend who is very good with this stuff has given me his take on it, but I wondered if

相关标签:
1条回答
  • 2021-01-07 01:37

    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))
    
    0 讨论(0)
提交回复
热议问题