Reputation: 366
I use rolify in my Rails app and I'm trying to stop the process "remove role" with callback but it does not seem to do what I want.
rails 6.0.3 / rolify 5.3.0
this is my code
class User < ApplicationRecord
rolify before_remove: :check_remove_role
# ...
def check_remove_role(role)
puts 'Remove role'
# Do not remove role if User is the only super_admin
return false if role.name=='super_admin' && User.with_role(role.name).count == 1
end
end
When I call user.remove_role(role) the callback pass, but the "removing process" does not stop even if the callback return 'false'.
Is there something wrong in my code ? or do I have to do it another way (maybe I can not use callback for this) ?
Upvotes: 0
Views: 205
Reputation: 2986
It looks like you are hoping to use these callbacks like an ActiveRecord validation. They are different things. The callback is simply a way to run code before and after the role record is created/destroyed, it is not used to control whether the mutation code within is run.
Some options:
can_remove_role?(:role)
and then test that in your controller before making the change.change_role?
or similar policy where you define what is a legal role change for the @record
and then call the authorize on it.Option 3 is nice, because it provides a DRY location to make more rules regarding what can and cannot be done with your Users. Perhaps do some searches for tutorials on how Pundit and Rolify can be used together.
Upvotes: 1
Reputation: 356
Looks like callbacks won't help you. According to wiki
Trying to remove a global role where the user has a role with the same name on a resource will remove that scoped role (whatever the scope is)
Trying to remove a class scoped role where the user has an instance scoped role with the same name on a resource will remove that instance scoped role
Trying to remove a role scoped to a resource class where the user has a global role won't remove it
Trying to remove a role scoped to a resource instance where the user has a global role won't remove it
Upvotes: 0