Rails 4 and Devise: Allow sending email under certain conditions

I am currently working on a system where an email is only required if the user is not a student, and a username is required if the user is a student. So here is what I did in my model:

class User < ActiveRecord::Base validates :email, presence: true, unless: :student? validates :username, presence: true, if: :student? end 

This works fine with username attributes, but for email I still get the error Email cannot be blank . I think Devise has its own email validation rule.

How can I make this work, I mean overriding Devise to validate email presence?

thanks

+6
source share
2 answers

Does the developer have an email_required? method email_required? which can be overridden using some custom logic.

 class User < ActiveRecord::Base validates :username, presence: true, if: :student? protected def email_required? true unless student? end end 
+4
source

I think Devise uses email as the key in its model.

add_index :users, :email, unique: true

If you used the generated migrations to create, you can make the user_name wrap key.

add_index :users, :user_name, unique: true
remove_index(users, column: users)
change_column :users, :email, :string, :null => true

0
source

All Articles