リモートで働くプログラマーの検索結果

リモ太がググったことの覚書

deviseのユーザー登録時に利用規約に同意のチェックボックスを追加する

よくあるユーザー登録時に利用規約同意用のチェックボックスを追加したい

モデルに同意チェックボックス用のvalidatesを追加

acceptance: trueを使うことで特に項目を追加したりしなくてもよい

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :confirmable, :lockable, :timeoutable, :trackable

  validates :agreement_terms, allow_nil: false, acceptance: true, on: :create # <-- 追加
end

deviseのstrong parameterに上で追加した同意チェックボックス用の項目を追加

class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller? # <-- 追加

  protected

  def configure_permitted_parameters # <-- 追加
    devise_parameter_sanitizer.permit(:sign_up, keys: [:agreement_terms])
  end
end

viewに同意チェックボックスを追加

ここではhamlとsimple_formを使っている例なので適時いい感じに

%h1= t('devise.registrations.new.sign_up')
= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f|
  = f.error_notification
  .form-inputs
    = f.input :email
    = f.input :password
    = f.input :password_confirmation
    -# 以下の1行追加
    = f.input :agreement_terms, as: :boolean, label: '利用規約・プライバシーポリシーに同意する' 
  .form-actions
    = f.button :submit, t('devise.registrations.new.sign_up'), class: 'btn btn-primary'
= render "users/shared/links"

以上で追加できる