#2 deviseでログイン機能の作成

第2回では、メールアドレスを利用したユーザー登録・ログイン機能をつくります。

deviseの導入

参考サイトを見ながらdeviseを導入します。

deviseとは

ユーザー登録して、送られてきたメールのリンクをクリックして本登録して、ログインして、パスワード忘れたら再設定して、何回もログインミスったらアカウントロックして…などといった認証系アプリに必要な機能を簡単に追加できる便利なgemです。

Gemfileにdeviseを追加します。

gem 'devise'
gem 'slim-rails' # slimを利用する場合
$ bundle install

deviseの設定

$ rails generate devise:install
Some setup you must do manually if you haven't yet:

  1. Ensure you have defined default url options in your environments files. Here
     is an example of default_url_options appropriate for a development environment
     in config/environments/development.rb:

       config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

     In production, :host should be set to the actual host of your application.

  2. Ensure you have defined root_url to *something* in your config/routes.rb.
     For example:

       root to: "home#index"

  3. Ensure you have flash messages in app/views/layouts/application.html.erb.
     For example:

       <p class="notice"><%= notice %></p>
       <p class="alert"><%= alert %></p>

  4. If you are deploying on Heroku with Rails 3.2 only, you may want to set:

       config.assets.initialize_on_precompile = false

     On config/application.rb forcing your application to not access the DB
     or load models when precompiling your assets.

  5. You can copy Devise views (for customization) to your app by running:

       rails g devise:views

上から順に設定していきます。

  • デフォルトURLの設定。指定通りに追加しました。
  • root_url。コントローラを作成後、設定しました。
$ rails g controller welcome index
root 'welcome#index'
  • フラッシュの表示。指定通りに追加しました。
  • Rails4.2.6を使用しているので不要です。
  • Viewファイルの作成。指定通りに実行しました。

slimを利用する場合

gemにhtml2slimを追加して、下記のコマンドで変換を行いました。

for file in app/views/devise/**/*.erb; do erb2slim $file ${file%erb}slim && rm $file; done

参考:How To: Create Haml and Slim Views

Userモデルの作成

$ rails g devise User

今回は、マイグレーションファイルに変更を加えずに実行します。

$ rake db:migrate

Viewの編集

参考サイトから拝借したソースコードを編集してapplication.html.erbに貼付け、無事に動く状態になりました。

<% if user_signed_in? %>
    <strong><%= link_to current_user.email, root_path %></strong>
    <%= link_to 'Settings', edit_user_registration_path %>
    <%= link_to 'Log out', destroy_user_session_path, method: :delete %>
<% else %>
    <%= link_to 'Sign up', new_user_registration_path %>
    <%= link_to 'Log in', new_user_session_path %>
<% end %>

f:id:tsyknsr:20160628191453p:plain

f:id:tsyknsr:20160628191502p:plain

参考サイト