开发者

Is there a way to have three way habtm associations in rails / activerecord?

开发者 https://www.devze.com 2022-12-30 00:21 出处:网络
Often three (or more) way associations are needed for habtm associations. For instance a permission model with roles.

Often three (or more) way associations are needed for habtm associations. For instance a permission model with roles.

A particular area of functionality has many users which can access many areas.开发者_Go百科

The permissions on the area are setup via roles (habtm)

The user/roles association is also habtm

The permissions (read, write, delete, etc) are habtm towards roles.

How would that be best done with rails/activerecord?


I'm not sure if you are just using Role based user permissions as an example, or if that is actually your goal.

Nested habtm relationships are easy in Rails, though I would highly recommend Nested has_many :through, just set them up as you would imagine:

class Permission < ActiveRecord::Base
end

#this table must have permission_id and role_id 
class PermissionAssignment < ActiveRecord::Base
  belongs_to :permission
  belongs_to :role
end

class Role < ActiveRecord::Base
  has_many :users, :through => :role_assignments
  has_many :permissions, :through => :permission_assignments
end

#this table must have user_id and role_id     
class RoleAssignment < ActiveRecord::Base
  belongs_to :role
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :roles, :through => :role_assignments
end


This question about rails and RBAC (role-based authentication control) has a bunch of useful samples that provide the answer to this question and also sample implementations of your example.

0

精彩评论

暂无评论...
验证码 换一张
取 消