lkartono
lkartono

Reputation: 2393

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

Upvotes: 7

Views: 3884

Answers (2)

lkartono
lkartono

Reputation: 2393

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

Upvotes: 9

Sinan Guclu
Sinan Guclu

Reputation: 1087

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

Upvotes: 1

Related Questions