1
0

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.

Ruby on Rails [学習記録-第8章-]

Posted at

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

  • deviseでログイン機能を実装すると、ログイン・サインアップ画面は自動的に生成されるがビューファイルとしては生成されない。これは、deviseのGem内に存在するビューファイルを読み込んでいるため。
  • ビューファイルに変更を加えるためには、deviseのコマンドを利用してビューファイルを生成する必要がある。
    *下記のコマンドを実行し、devise用のビューファイルを生成する。
$ rails g devise:views
  • サインアップ画面はapp/views/devise/registrations/new.html.erb、ログイン画面のビューはapp/views/devise/sessions/new.html.erbというビューファイルが対応しています。

カラムを追加するマイグレーションファイルの作成

  • カラムを追加するマイグレーションファイルを作成するためには、下記のコマンドを実行。
$ rails g migration Addカラム名To追加先テーブル名 追加するカラム名:型
sample
$ rails g migration AddIntroductionToUsers introduction:text
# usersテーブルにintroductionカラムをtext型で追加するマイグレーションファイルの作成

登録画面のビューを編集

  • DB側の準備は整ったので、ユーザーの新規登録画面にニックネームを登録するためのフォームを追加。

text_field:maxlengthオプション

  • maxlengthは、text_fieldというinputタグを生成するヘルパーメソッドにつけることができるオプション。
registrations/new.html.erb
<div class="field">
  <%= f.label :nickname %> <em>(6 characters maximum)</em><br />
   <%= f.text_field :nickname, autofocus: true, maxlength: "6" %>
</div>

ストロングパラメーターを編集

  • 通常のリクエストの場合は、コントローラに記述してあるストロングパラメーターで受け取れるパラメーターを制限。
  • しかし、deviseでログイン機能を実装した場合のパラメーターの受け取り方は通常とは異なる。
  • ログイン時に送られてくるパラメーターを制限するストロングパラメーターは、deviseのGem内に記述されているため編集することはできない。
  • deviseでは初期状態でサインアップ時にメールアドレスとパスワードのみを受け取るようにストロングパラメーターが設定してあるので、追加したキーのパラメーターは許可されていない。
  • 追加のパラメーターを許可したい場合は、application_controllerにおいてbefore_actionにconfigure_permitted_parametersメソッドを設定する。
application_controller.rb
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:nickname])
  end
end
1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?