Question

I have one user model and within that model I have roles (admin and general). I am using Devise https://github.com/plataformatec/devise and CanCan https://github.com/ryanb/cancan.

An admin creates the master account during their registration and then can register other users as well as edit their accounts. This works.

Finally, I have changed it so that the users can log in using their username and not email because email is not necessary for the general user.

My current (main) registration form (used only by the admin) requires the following information: First Name; Last Name: Email; Username and Password. I know that it is necessary for me to both validate certain fields and also make it so that usernames and email are unique. Both I know how to do.

USER MODEL

validates :username, :email, :password, presence: true

DB MIGRATE

add_index :users, :email,  :unique => true

My problem is that when the admin creates the other users email is not applicable and also I want to include additional fields. Because email is not necessary and because I am using a single user model, validating that field or making it unique will not work. Or I do not think it will work?

If I do not want to separate out the model is their another direction I can approach this to solve the problem. I am thinking two registration forms -- but still the issue of validation and uniqueness will be present.

Any guidance would be appreciated.

Was it helpful?

Solution

Have you considered a method in your application controller to create users like so:

def create_new_user
    u = User.create(:email => "guest_#{Time.now.to_i}#{rand(99)}@example.com", :password => params([:password]), :username => params([:username]))
    u.save!
end

You could create a form that admin could use to get username and any other parameters you need to this method.

Alternatively, you can generate the devise views and customize them to suit your needs.

rails generate devise:views

Then you can move :email into a hidden field (it will still be present and so pass validation) in the form and set it randomly like above. This will handle the unique issue. You can also add other attributes like you wanted.

Keep in mind though that if you want to create a Devise resource while signed in as a devise resource, you'll have to customize a few things in the registrations controller.

Devise has some good info on custom views. https://github.com/plataformatec/devise

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top