Question

I'm working with Rails 4 and Devise 3.0.0 and am new to using these new strong paramters. I added a username to the User model using the documentation on the Devise wiki. The problem I'm running into is the strong parameters change in Rails 4.

How do I add the :login attribute to the user model to enable logging in with either the username or email?

Was it helpful?

Solution

From the rails4 readme on devise: https://github.com/plataformatec/devise/tree/rails4#strong-parameters

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

  protected

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

OTHER TIPS

@justin.chmura

Here is a gist of how we ended up getting it working.
https://gist.github.com/AJ-Acevedo/6077336

Gist contains:
app/controllers/application_controller.rb
app/models/user.rb
config/initializers/devise.rb

You should make sure that you include the

attr_accessor :login

in the user model. Here is where I found the question explaining that attr_accessible is deprecated.

Rails 4 + Devise Login with email or username and strong parameters

Difference between attr_accessor and attr_accessible

This is what my app/models/user.rb file looks like.

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

attr_accessor :login

  def self.find_first_by_auth_conditions(warden_conditions)
    conditions = warden_conditions.dup
    if login = conditions.delete(:login)
      where(conditions).where(["username = :value OR lower(email) = lower(:value)", { :value => login }]).first
    else
      where(conditions).first
    end
  end

  validates :username,
  :uniqueness => {
    :case_sensitive => false
  }
end

It will works fine if you add an module in config/initializers as followings with all parameters,

File config/initializers/devise_permitted_parameters.rb with following contents:

module DevisePermittedParameters
  extend ActiveSupport::Concern

  included do
    before_filter :configure_permitted_parameters
  end

  protected

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

end

DeviseController.send :include, DevisePermittedParameters
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top