11

I'm new to RoR and stuck with this devise problem. I want to allow users to sign in with email OR username (registration with username is already ok).

I followed these articles: Article 1 and Article 2 and you can see the result below:

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 = [ :login ] ...

result

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

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

I don't understand why it doesn't work because I specified that for "sign_in" permit :login for User.

hansottowirtz
  • 664
  • 1
  • 6
  • 16
Dragu
  • 3,242
  • 2
  • 16
  • 15

1 Answers1

8

The problem is with the field "login", remove :authentication_keys => [:login] and add attr_accessor :login in your User model.

David Tuite
  • 22,258
  • 25
  • 106
  • 176
rb512
  • 6,880
  • 3
  • 36
  • 55
  • 2
    Thanks you so much, it works just by adding attr_accessor :login ! I thought that the "attr_accessor" had been replaced by strong parameters since Rails 4. – Dragu Aug 02 '13 at 23:02
  • nope, attr_accessible is deprecated. here's more on it : http://stackoverflow.com/questions/3136420/difference-between-attr-accessor-and-attr-accessible – rb512 Aug 02 '13 at 23:19
  • @Dragu `attr_accessible` was replaced by strong parameters. `attr_accessor` creates the setter/getter methods, in this case, `login`. It is also creating an instance variable of `@login` – scarver2 Aug 15 '14 at 14:31