Rails3 × Deviseでユーザー認証機能を追加する
第12回: ユーザー認証(1) - Ruby on Rails 3.0 日記 - Ruby on Rails with OIAX
第13回: ユーザー認証(2) - Ruby on Rails 3.0 日記 - Ruby on Rails with OIAX
ここの記事参考にRails3にユーザ認証機能を追加したので、メモしておきます。
Deviseのインストール〜準備
Gemfileに下記の一行を追加しました。
gem "devise" , ‘1,1,5’
必要なスクリプトを実行しました。
$ bundle install # Deviseをインストール $ rails g devise:install # Deviseをアプリに組み込み $ rails g controller welcome index # トップページを作成 $ rails g devise:views # Viewを生成 $ rails g devise user # Userモデルを生成 $ rake db:migrate # マイグレーションを実行
Deviseの設定
1. メールの設定
config/environments/development.rb
Hoge::Application.configure do (省略) config.action_mailer.default_url_options = { :host => 'localhost:3000' } end
2. ルーティングの設定
config/routes.rb
Todo::Application.routes.draw do (省略) # You can have the root of your site routed with "root" # just remember to delete public/index.html. root :to => "welcome#index" # トップページ devise_for :users # ユーザ登録、ログインなど get 'tasks', :to => 'tasks#index', :as => :user_root # ユーザー認証後のリダイレクト先 end
3. Viewの修正
app/views/layouts/application.html.erb
<body> <!-- ここから2行追加 --> <p class="notice"><%= notice %></p> <p class="alert"><%= alert %></p> <%= yield %> </body>
app/views/welcome/index.html.erb
<h1>Hogeへようこそ</h1> <% if current_user %> <span><%= link_to 'ログアウト', destroy_user_session_path, :method=>'delete' %></span> <% else %> <span><%= link_to 'ログイン', new_user_session_path %></span> <span><%= link_to 'ユーザー登録', new_user_registration_path %></span> <span><%= link_to 'パスワード再発行', new_user_password_path %></span> <% end %>
4. Controllerの修正
※ 認証機能をコントローラに追加する場合は、以下のようにします。
class HogeController < ApplicationController before_filter :authenticate_user! ... end