(Rails 3.2.6, Ruby1.9, devise2.1.2)
ようするに
パスワードとユーザ名
もしくは
パスワードとE-mail
どちらでもログインできるようにしてみる。
デフォルトは E-mail と password
ユーザ名もしくはE-mailでサインインできるようにする
テスト用プロジェクト作成
$ rails new testdevise --skip-bundle $ cd testdevise/
devise インストールなど
Gemfile
add
gem 'devise'
shell
$ bundle install : $ rails generate devise:install $ rails generate devise User username:string $ rake db:migrate
user.rb
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :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 # Virtual attribute for authenticating by either username or email # This is in addition to a real persisted field like 'username' 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
Modify the views
shell
$ rails generate devise:views
sessions/new.html.erb
- <p><%= f.label :email %><br /> - <%= f.email_field :email %></p> + <p><%= f.label :login %><br /> + <%= f.text_field :login %></p>
registrations/new.html.erb
+ <p><%= f.label :username %><br /> + <%= f.text_field :username %></p> <p><%= f.label :email %><br /> <%= f.email_field :email %></p>
registrations/edit.html.erb
+ <p><%= f.label :username %><br /> + <%= f.text_field :username %></p> <p><%= f.label :email %><br /> <%= f.email_field :email %></p>
確認用にview編集
application.html.erb
: <body> <% 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 %> :
確認用にcontroller 作成
$ rails generate controller Blog index rm public/index.html
before_filter :authenticate_user!
routes.rb
root :to => 'blog#index'