Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 + Devise 3.0.0 Adding Username

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?

like image 442
Justin Chmura Avatar asked May 23 '13 13:05

Justin Chmura


3 Answers

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
like image 159
Jesse Wolgamott Avatar answered Nov 18 '22 10:11

Jesse Wolgamott


@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

like image 42
AJ. Avatar answered Nov 18 '22 09:11

AJ.


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
like image 2
Daniel Avatar answered Nov 18 '22 09:11

Daniel