11

我是 RoR 的新手,遇到了这个设计问题。我想允许用户使用电子邮件或用户名登录(使用用户名注册已经可以了)。

我关注了这些文章: 第 1条和第 2 条,您可以看到以下结果:

application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_filter :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password) }
    devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:login, :password, :remember_me) }
  end
end

用户.rb

class User < ActiveRecord::Base
    devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]

  validates_uniqueness_of :username
  validates_presence_of :username
  validates :username, length: { in: 4..20 }

  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      
end

新的.html.erb

<%= form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %>
  <div><%= f.label :login, "Pseudo ou email" %><br />
  <%= f.text_field :login, :autofocus => true %></div>
...

设计.rb

... config.authentication_keys = [ :login ] ...

结果

Showing /home/action/workspace/rchq/app/views/devise/sessions/new.html.erb where line #5 raised:

undefined method `login' for #<User:0x000000033996a0>

我不明白为什么它不起作用,因为我为“sign_in”指定了允许:用户登录。

4

1 回答 1

8

问题在于“登录”字段,删除:authentication_keys => [:login]并添加 attr_accessor :login到您的User模型中。

于 2013-08-02T22:45:53.283 回答