1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Rails] deviseの導入手順

Posted at

手順1

Gemfile
gem 'devise'
ターミナル
$ bundle
$ rails g 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. You can copy Devise views (for customization) to your app by running:
       rails g devise:views
===============================================================================

手順2

・ビューの作成

ターミナル
$ rails g devise:views

・Userモデルの作成

ターミナル
$ rails g devise User
# この時にmigrationファイルが作成されるのでusersテーブルに追加したいカラムを記述すると良い。
# 今回はnameカラムを追加するとする。

$ rails db:migrate

手順3

手順2で追加したnameカラムを使用できるように設定します。

app/controllers/application_controller.rb

application_controller.rb
class ApplicationController < ActionController::Base
  #このコードがあると、Railsで生成されるすべてのフォームとAjaxリクエストにセキュリティトークンが自動的に含まれます。セキュリティトークンがマッチしない場合には例外がスローされます。(Railsガイド)
  protect_from_forgery with: :exception

  before_action :configure_permitted_parameters, if: :devise_controller?

  protected
  
  #configure_permitted_parametersはストロングパラメータを設定するメソッド。
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
    devise_parameter_sanitizer.permit(:account_update, keys: [:name])
  end
end

基本的な操作は以上。

番外編

ユーザー編集をパスワード無しで行う。

registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController

  protected

  def update_resource(resource,params)
    resource.update_without_password(params)
  end
end

上のコードを使うにはroutingを変更しないといけない。

routes.rb
Rails.application.routes.draw do
  devise_for :users, controllers: { registrations: "registrations" }
end
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?