I've spent four days trying to achieve this role validation with no success, and I don't know if there is currently any way to do this behaviour with rolify. Here's a simple example of the situation I am having:
Suppose I have 3 types of roles:
- admin
- developer
- guest
A user can be both an admin and a developer, but cannot be also a guest.
A guest cannot be either an admin nor a developer.
I want the user to be able to set their roles on user registration, so I need to validate this behaviour before the user is created, and if it is not valid, the registration should fail and no user should be created.
I've read a lot of guides trying to achieve similar results, at least for the form submission, but there is no explanation about this type of validation.
Thanks in advance!
UPDATE: I've been searching for some ways to implement this, and this is the line of thought I've had during this time of struggles.
First: receive the roles selected as input and create a virtual attribute at the user model corresponding to this roles so that the params would look like this (simplified)
:params => { :user => {:email, :password, :roles => ["admin", "developer", "guest"]}}
if all roles are selected, and
:params => { :user => {:email, :password}}
if no role is selected.
Second: Do any type of validations with this virtual attribute(simplified)
Class User < ApplicationRecord
attr_accessor :roles
validate :roles_valid
def roles_valid
# Define custom validation
end
end
Third: if the record passes all the validations, create user and then assign the roles inside the registrations#new action
I think this method would work, but I am now having some problems with the virtual attribute, and it is that it doesn't seem to be connected to the roles params being received from the form. I guess I still don't understand how virtual attributes work, so I wish someone would clear me out on this one.