Hi.
I have a couple of best practices questions regarding polymorphic
associations, naming join tables and user permissions.
Currently I have implemented the user authentication model from the
rails recipes book. Basically it goes something like this:
MODEL CLASSES:
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
end
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
has_and_belongs_to_many :rights
end
class Right < ActiveRecord::Base
has_and_belongs_to_many :roles
end
TABLES:
users
rights
roles
rights_roles (habtm join table)
roles_users (habtm join table)
All fairly standard stuff.
As my application has evolved I wish to add roles to other things as
well such as groups of users. What I don’t want is to have to create
another join table roles_groups.
I think this can be re-factored using polymorphic associations like so.
NEW MODEL CLASSES:
class User < ActiveRecord::Base
has_many :responsibilities, :as => :roleable
has_many :roles, :through => : responsibilities
end
class Group < ActiveRecord::Base
has_many :responsibilities, :as => :roleable
has_many :roles, :through => : responsibilities
end
class Responsibilities < ActiveRecord::Base
belongs_to :group
belongs_to :user
end
class Role < ActiveRecord::Base
has_many :responsibilities
has_many :users, :through => :responsibilities
has_and_belongs_to_many :rights
end
class Right < ActiveRecord::Base
has_and_belongs_to_many :roles
end
NEW TABLES:
users
rights
roles
groups
responsibilites
rights_roles
Has anyone got any comments / corrections / ideas about this one?
Maybe a more suitable join model name than responsibilities
Leevi G.
Front End Developer - User Interface Designer
www.leevigraham.com | Skype Me: leevi_graham
MSN Messenger: [email protected]
Download My VCard