“Email can't be blank” Devise using username o

2019-06-20 09:14发布

问题:

I was following this how-to on How To: Allow users to sign in using their username or email address and did all the steps detailed there but when I try to register via the registrations/new.html.erb form I get this error:

Email can't be blank

In my model I have:

devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

attr_accessible :username, :email, :password, :password_confirmation, :remember_me

attr_accessor :login
attr_accessible :login

and

def self.find_first_by_auth_conditions(warden_conditions)
    conditions = warden_conditions.dup
    if login = conditions.delete(:login)
      where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
    else
      where(conditions).first
    end
  end

any advice with this problem?

======= UPDATE

I found something here ■[rails]How to use Devise and Rails , without EMail here it is something like:

  # Email is not required
  def email_required?
    false
  end

With that added in my model I can create a record with username and leaving the email field blank, but when I try to create a second record without email the database rises an error:

Mysql2::Error: Duplicate entry '' for key 'index_parents_on_email':...

Should I use this, remove the index from my table in the database, and just validate the username in the model? because I don't really need the email field on that model.

回答1:

Update

Asiniy's answer below actually works like a charm (:

Original (who knew?)

Your problem is the index on the mysql table, you might remove it from your migrations, but I'm not sure that will solve your problem. Not using the email in Devise is tricky, I would suggest a workaround like a fake email out of the username, something like this

"#{user.username}@fake.me"

It's not very clean but I see devise doing something similar for passwords when you use omniauth.

Rails 4 and Strong Parameters

I got into this problem for username in rails 4, and I had to configure the permitted parameters as below for sign_up:

class ApplicationController < ActionController::Base

  before_filter :configure_permitted_parameters, if: :devise_controller?

  protected

    def configure_permitted_parameters
      devise_parameter_sanitizer.for(:sign_up) do |u|
        u.permit :username, :email, :password, :password_confirmation
      end
    end
end

This is described in Devise Doc



回答2:

Normal solution

class User < AR::Base
  devise_for tralala

  def email_required?
    false
  end
end

Please refer to the https://github.com/plataformatec/devise/blob/master/lib/devise/models/validatable.rb#L29