1 min read

Rails attr_accessor validations and Devise

Rails attr_accessor validations and Devise

Recently I was working on a Ruby on Rails form to handle user registrations using Devise. The client wanted me to add a checkbox for the users to confirm their acceptance of the Terms of Service before creating their accounts. Since signing up for an account successfully should only be allowed after the user confirmed their acceptance (at least theoretically), I decided not to add a database field and used attr_accessor instead.

To ensure that the user checked this field before they can create an account, I also added a Rails acceptance validator. So my user model ended up like:class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
    :confirmable, :recoverable, :rememberable,
    :trackable, :validatable   attr_accessor :terms_of_service
  validates :terms_of_service, acceptance: true, on: :createend

This should have worked in theory but I had no such luck. After checking online and confirming my syntax, everything still seemed to be correct.

Luckily I have just added some custom fields to my user model and Devise instructions were still fresh on my head so I remembered that due to strong_parameters in Rails 4, the attribute was not being passed to the model automatically. This is explained in further detail on Devise repo but basically I had to add the following code to my application_controller.rb file and voilà, everything started working:class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if:
     :devise_controller?   protected   def configure_permitted_parameters
     devise_parameter_sanitizer.for(:sign_up) << [:first_name,
        :last_name, :terms_of_service]
  endend