LoginSignup
4
3

More than 5 years have passed since last update.

Rails Devise で DB カラムに依存しない項目を追加する acceptance

Posted at

やりたいこと

image.png

ユーザー登録時に 利用規約に同意する を実現したいが,わざわざそれ用のカラムをつくるほどでもない.

このメソッドは、フォームが送信されたときにユーザーインターフェイス上のチェックボックスがオンになっているかどうかを検証します。ユーザーにサービス利用条項への同意、何らかの文書に目を通すことなどを義務付けるのに使用するのが典型的な利用法です。Rails Guide > acceptance

このヘルパーを用いる

確認環境

  • devise (4.3.0)
  • rails (5.1.6)

Model 更新

モデルにチェックしたかどうかのフラグを持たせる.
登録時のみバリデーションしたいので on: :create でスコープを絞る.

app/models/user.rb
class User < ApplicationRecord
    validates :registration_check, acceptance: true, on: :create
end

attr_accessor などでアクセサを生やしているサンプルもあるが,この validates を記述するだけでよい.

'acceptance'はデータベースに保存する必要はありません。保存用のフィールドを作成しなかった場合、ヘルパーは単に仮想の属性を作成します。Rails Guide > acceptance

なお当然だが,この記述をしないと View でエラーになる.
image.png

若干ハマったのだが,次項の Strong Parameter の設定をしないと,このバリデーションは正常に動作せず,チェックを入れなくても登録ができてしまうので注意.

Strong Parameter / Controller 更新

Devise Controller を Override してカスタマイズする.

他にも Application Controller で before_action などでやるやり方もあるみたいだが,ApplicationController には書きたくなかったので採用しなかった.

Controller の雛形を生成し,該当箇所をコメントアウトして有効化する.

$ bundle exec rails g devise:controllers users
app/controllers/users/registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
   before_action :configure_sign_up_params, only: [:create]

   •••

   protected

   # If you have extra params to permit, append them to the sanitizer.
   def configure_sign_up_params
     devise_parameter_sanitizer.permit(:sign_up, keys: [:registration_check])
   end
end

View 更新

View の雛形を生成し, registration_check を追加.

$ rails g devise:views users
app/views/devise/registrations/new.html.slim
.field
    = f.check_box :registration_check
    = f.label :registration_check

参考

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