LoginSignup
0
0

More than 3 years have passed since last update.

Rails deviseの使い方

Last updated at Posted at 2021-01-23

devise(超初心者の備忘録)

どうも、はじめまして!yukkyです。今回が初投稿でQiitaの書き方もよくわかっていないですが記録を残さないとすぐ忘れてしまうため、頑張って書いていきたいと思います。題名にも書きましたが自分はがつくレベルの初心者ですので間違えがあったら(多分いっぱいあります。。)コメントで教えてくれると嬉しいです。さっき調べてみたら初めてvisual studioを入れた日(=初めてプログラムに触れた日)が2020/9/9でした(-_-;)まだ4.5か月ほどしかしてないですね。。

deviseでできること

ログイン機能が使えるようになる

使い方

まず練習用アプリとしてlogin_appを作る

rails new login_app 

gemにdeviseを追加

Gemfile
gem 'devise'
bandle install
rails g devise:install

すると以下の画面が出てくれば成功


Depending on your application's configuration some manual setup may be required:

  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.

     * Required for all applications. *

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

       root to: "home#index"

     * Not required for API-only Applications *

  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>
     * Not required for API-only Applications *

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

       rails g devise:views

     * Not required *

===============================================================================

何やらセットアップをしなきゃいけないらしい(1番をしてなくて後で痛い目にあいました..)
1 config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }をconfig\environments\development.rbに追加

2 ここは後でhomeコントローラを作るとき自動でやってくれるので大丈夫

3

<%= notice %>


<%= alert %>


これをつけるとポップアップが出るよ

4 後でやるので大丈夫

rails g devise User

でdevise用のユーザーモデルが作れる。今回は名前でログインしたいのでmigrateする前にnameカラムを作る

**_devise_create_users.rb(**には日付が自動で入る)
t.string :name

を追記。その後migrate

rails db:migrate

新規登録フォーム、ログインフォーム作成

rails g devise:views

これでviewが出来る。
新規登録フォームのviewはapp\views\devise\registrations\new.html.erb
ログインフォームのviewはapp\views\devise\sessions\new.html.erb
中身を見るとデフォルトではメアドでログインになっているので名前に変更。
(VSCcodeを使っている方は、cmd(ctrl) + pを押すとファイル名で検索できます.)
(VSCcodeを使っている方は、cmd(ctrl) + fを押すと文字列で検索できます)

app\views\devise\sessions\new.html.erb
<h2>Log in</h2>

<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>

<!-- ここから追加 --!>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name, autofocus: true, autocomplete: "name" %>
  </div>
<!-- ここまで追加 --!>

<!-- ここから削除 --!>
  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true, autocomplete: "email" %>
  </div>
<!-- ここまで削除 --!>

さらに新規登録画面でも名前を追加(注:さっきは変更だったけど今度は追加)

app\views\devise\registrations\new.html.erb
<h2>Sign up</h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= render "devise/shared/error_messages", resource: resource %>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true, autocomplete: "email" %>
  </div>
<!-- ここから追加 --!>
  <div class="field"> 
    <%= f.label :name %><br />
    <%= f.text_field :name, autofocus: true, autocomplete: "name" %>
  </div>
<!-- ここまで追加 --!>

を追加。これだとまだ名前を送れないので新規作成(singn up)名前の情報を送ることを許可する設定を行う

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
<!-- ここから追加 --!>
  before_action :configure_permitted_parameters, if: :devise_controller? 

  private

    def configure_permitted_parameters
      devise_parameter_sanitizer.permit(:sign_up,keys:[:name])
    end
end

自分の場合keys:[:name,:email]としないとemailが送れなかった。デフォルトでemailは許可されているはずなのだが...

さらにログイン(sign in)するとき名前の情報を送ることを許可する設定を行う

config\initializers\devise.rb
<!-- ここを削除 --!>
  # config.authentication_keys = [:email]
<!-- ここを追加 --!>
  config.authentication_keys = [:name]

しかしこれではログインしてもホームパス(Yay! You’re on Rails!のところ)に行ってしまうため画面を作る。

rails g controller home top (ログインした後行く場所)
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller? 
  <!-- ここから追加 --!>
  def after_sign_in_path_for(resource)
    home_top_path
  end
  private
<!-- ここまで追加 --!>
    def configure_permitted_parameters
      devise_parameter_sanitizer.permit(:sign_up,keys:[:name])
    end
end

さらにホームトップにログアウトボタンを作る。

app\views\home\top.html.erb
<%= link_to "ログアウト", destroy_user_session_path, method: :delete %>

これで一通り機能が完成!ありがとうございました。

0
0
0

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
0
0