"电子邮件不能为空"使用用户名或电子邮件设计

Mr_*_*zle 6 devise ruby-on-rails-3

我正在关注如何:允许用户使用他们的用户名或电子邮件地址登录并执行所有详细步骤,但当我尝试通过registrations/new.html.erb表单注册时,我收到此错误:

Email can't be blank
Run Code Online (Sandbox Code Playgroud)

在我的模型中,我有:

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

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

attr_accessor :login
attr_accessible :login
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

有这个问题的任何建议吗?

=======更新

我在这里发现了一些东西■[rails]如何使用Devise和Rails,没有电子邮件,这里是这样的:

  # Email is not required
  def email_required?
    false
  end
Run Code Online (Sandbox Code Playgroud)

随着在我的模型中添加,我可以使用用户名创建记录并将电子邮件字段留空,但是当我尝试创建没有电子邮件的第二条记录时,数据库会出现错误:

Mysql2::Error: Duplicate entry '' for key 'index_parents_on_email':...
Run Code Online (Sandbox Code Playgroud)

我应该使用它,从数据库中的表中删除索引,只是验证username模型中的?因为我真的不需要该模型上的电子邮件字段.

eco*_*gic 12

更新

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

原创(谁知道?)

你的问题是mysql表上的索引,你可能会从迁移中删除它,但我不确定这会解决你的问题.不使用在设计的电子邮件是棘手的,我会建议一个解决办法像假的电子邮件出来的username,这样的事情

"#{user.username}@fake.me"
Run Code Online (Sandbox Code Playgroud)

它不是很干净,但是当你使用omniauth时,我会看到设计为密码做类似的事情.

Rails 4和强参数

username在rails 4中遇到了这个问题,我必须配置允许的参数,如下所示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
Run Code Online (Sandbox Code Playgroud)

这在Devise Doc中有所描述


asi*_*niy 6

正常解决方案

class User < AR::Base
  devise_for tralala

  def email_required?
    false
  end
end
Run Code Online (Sandbox Code Playgroud)

请参阅https://github.com/plataformatec/devise/blob/master/lib/devise/models/validatable.rb#L29