14
13

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

acceptedカラムを追加

rails g migration AddAcceptedToUsers accepted:boolean
rails g migration Addカラム名Toテーブル名 カラム名:boolean

必要なオプション default: false, null: false

マイグレーション.rb
def change
  add_column :users, :accepted, :boolean, default: false, null: false
end

bundle exec rake db:migrate

ストロングパラメータを追加

application_controller.rb
class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?
  protect_from_forgery with: :exception

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:email, :password, :password_confirmation, :accepted)}
  end

end

バリデーションを追加

user.rb
  validates :accepted, presence: {message: 'を入力してください'}

カラムを日本語化

ja.yml
user:
  accepted: 利用規約、及び、個人情報の取扱に同意する

サインアップ後のリダイレクト先をrootに変更

registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController

  protected

  # サインアップ後のリダイレクト先をrootに変更
  def after_sign_up_path_for(resource)
    root_path
  end

  def after_update_path_for(resource)
    user_path(current_user)
  end

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

end

フォームを追加

views/devise/registrations/new.html.erb
<div class="field text-left">
  <%= f.check_box :accepted ,{},checked_value = "true",unchecked_value = "false" %>
  <%= f.label '利用規約、及び、個人情報の取扱に同意する' %>
</div>
14
13
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
14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?