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

时间:2012-07-26 21:46:12

标签: ruby-on-rails-3 devise

我在How To: Allow users to sign in using their username or email address上关注此操作方法,并完成了所有详细步骤,但当我尝试通过registrations/new.html.erb表单注册时,我收到此错误:

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]How to use Devise and Rails , without EMail发现了一些东西:

  # Email is not required
  def email_required?
    false
  end

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

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

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

2 个答案:

答案 0 :(得分:12)

<强>更新

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

原创(谁知道?)

您的问题是mysql表上的索引,您可能会将其从迁移中删除,但我不确定这会解决您的问题。不使用Devise中的电子邮件很棘手,我建议使用username之类的虚假电子邮件,这样的事情

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

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

Rails 4和强参数

我在rails 4中遇到username的问题,我必须为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

答案 1 :(得分:6)

正常解决方案

class User < AR::Base
  devise_for tralala

  def email_required?
    false
  end
end

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

相关问题