Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 and Devise : Allow email blank on certain conditions

I'm currently working on a system where the email is only required if the user is not a student and 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 on username attributes, but for the email, I'm still getting Email cannot be blank error. I guess Devise has it's own email validation rule.

How can I make this works, I mean overriding Devise validate presence rule on email?

Thanks

like image 897
lkartono Avatar asked Mar 26 '14 00:03

lkartono


2 Answers

Devise has an email_required? method that can be overrided with some custom logic.

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

  protected

  def email_required?
    true unless student?
  end
end
like image 95
lkartono Avatar answered Sep 17 '22 02:09

lkartono


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

add_index :users, :email, unique: true

If you used the generated devise migrations you could make the user_name the key with a migration.

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

like image 32
Sinan Guclu Avatar answered Sep 19 '22 02:09

Sinan Guclu