LoginSignup
28

More than 5 years have passed since last update.

rails devise emailではなくてusernameでログインしたい

Last updated at Posted at 2013-11-27

rails devise emailではなくてユーザー名(username)でログインしたい

ex)https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address
http://d.hatena.ne.jp/CortYuming/20120705/p1

すでにrailsでdeviseが動いている状態

ユーザー名カラムの追加

$rails g migration AddUsernameToUsers username:string
$rake db:migrate

userモデルの修正

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

  # Setup accessible (or protected) attributes for your model
  attr_accessible :username, :email, :password, :password_confirmation, :remember_me
  # attr_accessible :title, :body

    attr_accessor :login
    attr_accessible :login

    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

devise の viewを作成

$rails g devise:views

devise の viewを編集

app/views/session/new.html.erb
$ diff new.html.erb new.html.erb.org
4,5c4,5
<   <div><%= f.label :login %><br />
<   <%= f.text_field :login, :autofocus => true %></div>
---
>   <div><%= f.label :email %><br />
>   <%= f.email_field :email, :autofocus => true %></div>
app/views/devise/registrations
new.html.erb
$ diff new.html.erb new.html.erb.org
6,8d5
<   <div><%= f.label :username %><br />
<   <%= f.text_field :username, :autofocus => true %></div>

edit.html.erb
$ diff edit.html.erb edit.html.erb.org
6,8d5
<   <div><%= f.label :username %><br />
<   <%= f.email_field :username, :autofocus => true %></div>

確認

$vi application.html.erb
<% if notice %>
      <p class="notice alert"><%= notice %></p>
    <% end %>
    <% if alert %>
      <p class="alert alert-error"><%= alert %></p>
    <% end %>

    <% if user_signed_in?%>
      <p><%= current_user.email %></p>
      <p class="btn"><%= link_to "Sign out", destroy_user_session_path, :method => :delete %></p>
    <% else %>
      <p class="btn"><%= link_to "Sign up", new_user_registration_path %></p>
      <p class="btn"><%= link_to "Sign in", new_user_session_path %></p>
<% end %>

ブラウザで確認
usernameでログインできた。

OK

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28