2013-08-02 16 views
11

私はRoRを初めて使用しており、この問題を解決しています。 ユーザーが電子メールまたはユーザー名でログインできるようにしたい(ユーザー名による登録はすでにOKです)。Rails 4 + Devise電子メールまたはユーザー名と強力なパラメータを使用してログインしてください

私はこれらの記事に続く: Article 1Article 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 

user.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 

new.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> 
... 

devise.rb

... config.authentication_keys =:それはので、動作しない理由を私は理解していない

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

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

[ログイン] ...

結果私は "sign_in"の許可を指定しました:ユーザーのログイン。

答えて

8

問題がフィールドにある「ログイン」、:authentication_keys => [:login]を削除し、あなたのUserモデルで attr_accessor :loginを追加します。

+2

ありがとう、attr_accessorを追加するだけで動作します:ログイン!私は、 "attr_accessor"がRails 4以降の強力なパラメータに置き換えられていると考えました。 – Dragu

+0

nope、attr_accessibleは推奨されていません。ここでそれ以上のことがあります:http://stackoverflow.com/questions/3136420/difference-between-attr-accessor-and-attr-accessible – rb512

+0

@Dragu 'attr_accessible'は強力なパラメータに置き換えられました。 'attr_accessor'はセッター/ゲッターメソッドを作成します。この場合は' login'です。 '@ login'のインスタンス変数も作成しています – scarver2

関連する問題