5
4

More than 5 years have passed since last update.

deviseの導入と実装

Last updated at Posted at 2019-04-03

deviseの導入と実装

Railsではdeviseを挿入することでユーザー登録機能を簡単に実装できます。

1.deviseの導入

Gemfileにgemを追加

Gemfile
gem 'devise'

bundle installを実行し、サーバーを再起動

$ bundle install
$ rails s

deviseの設定ファイルを作成

$ rails g devise:install

userモデルを作成

$ rails g devise user
$ bundle exec rake db:migrate
 #マイグレーションファイルに必要なカラム(name等)を設定した後に実行

deviseのビューファイルを作成

$ rails g devise:views

2.サインアップ機能

userのサインアップ時に名前を登録できるようにする

deviseでは初期状態でサインアップ時にメールアドレスとパスワードのみを受け取るようにストロングパラメーターが設定してあるので、
追加のパラメーターを許可したい場合は、application_controllerでbefore_actionにconfigure_permitted_parametersメソッドを設定する。

application_controller.rb
before_action :configure_permitted_parameters, if: :devise_controller?

protected

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

3.サインアウト、ログイン機能の実装

サインアウトボタンの設置

xxx.html.erb
<%= link_to "サインアウト", destroy_user_session_path, method: :delete, class: 'btn' %>

サインアウト後の遷移先を指定する

after_sign_out_path_forメソッド:サインアウト後のリダイレクト先URLを指定できる。

applocation_controller.rb
def after_sign_out_path_for(resource)
  '/users/sign_in' #サインアウト後はログイン画面に遷移
end

4.user編集機能を追加する

ルーティング

routes.rb
resources :users, only: [:edit, :update]

users_controller作成

$ rails g controller users

edit,updateの定義

users_controller
class UsersController < ApplicationController
    def edit
    end

    def update
        if current_user.update(user_params)
           redirect_to root_path #更新できた場合はTOP画面へ
        else
            render :edit #更新できない場合は編集画面に戻る
        end
    end

    private

    def user_params
        params.require(:user).permit(:name, :email)
    end
end

※redirect_toはデータの追加、更新、削除を行う時に、
 renderは単にデータの取得をする時に使用する。

ビューファイル作成

editボタン作成

xxx.html.erb
<%= link_to "edit" edit_user_path(current_user), class: 'btn' %>

/users/edit.html.erbを作成,updateボタンの設置

5
4
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
5
4