txwikinger
txwikinger

Reputation: 3034

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

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.

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?

Upvotes: 0

Views: 871

Answers (2)

Daniel Beardsley
Daniel Beardsley

Reputation: 20377

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

Upvotes: 2

corprew
corprew

Reputation: 2001

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.

Upvotes: 1

Related Questions