“电子邮件不能为空”使用用户名或电子邮件进行设计

问题描述:

我在如何:允许用户使用他们的用户名或电子邮件地址登录,并完成了所有步骤,但是当我尝试通过 registrations / new.html.erb 表单我收到这个错误:

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

在我的模型中,我有:

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

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

attr_accessor :login
attr_accessible :login

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

任何有此问题的建议?

=======更新

我在这里找到了一些内容■[rails]如何使用Devise和Rails,没有电子邮件在这里它是这样的:

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.

更新

Asiniy的答案实际上就像一个魅力(:

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

原始(谁知道?)

您的问题是mysql表中的索引,您可能会从迁移中删除它,但我不确定是否会解决您的问题,不使用电子邮件Devise是棘手的,我建议在用户名之外的假电子邮件的解决方法,像这样的

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"

不太干净,但是当您使用omniauth时,我会看到设计类似于密码。

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

Rails 4和强参数

我在rails 4中遇到了用户名的这个问题,而且我必须为配置允许的参数, sign_up

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

这在Devise Doc 中有描述