I'm trying to implement permissions and roles in a rails application. I have a role model and a permission model with a has_and_belongs_to_many relationship. I'm seeding the permissions inside the database and each permission has a unique id. Inside the role model i have a method with which i can add permissions to roles and it works but active record only saves the permission with the id = 1. In the console it says that the permission is assigned but when i type Role.first.permissions it doesn't show anything. I really don't understand what i am doing wrong since i also have the user model linked to the permission model in the same way, since i want to also be able to override the roles permissions on each individual user here it works for every permission. Maybe this double linkage between permissions, roles and users is causing the problem?
Here is my role.rb:
class Role < ActiveRecord::Base
has_and_belongs_to_many :permissions,
join_table: 'roles_permissions',
association_foreign_key: 'role_id'
has_many :users
def add_permission(perm_id)
self.permissions << Permission.find(perm_id)
end
def remove_all_permissions
self.permissions.each do |i|
i.delete(Permission.all)
end
end
def remove_permission(id)
self.permissions.delete(Permission.find(id))
end
end
Here is my user.rb:
class User < ActiveRecord::Base
has_and_belongs_to_many :permissions,
association_foreign_key: 'permission_id',
join_table: 'users_permissions'
belongs_to :role
def add_permission(perm_id)
self.permissions << Permission.find(perm_id)
end
def remove_all_permissions
self.permissions.each do |i|
i.delete(Permission.all)
end
end
def remove_permission(id)
self.permissions.delete(Permission.find(id))
end
end
And here is my permission.rb:
class Permission < ActiveRecord::Base
has_and_belongs_to_many :roles, join_table: 'roles_permissions'
has_and_belongs_to_many :users, join_table: 'users_permissions'
end
Aucun commentaire:
Enregistrer un commentaire