Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 - checkbox agreement validation fails on create new user registration using devise

I'm trying to include a "accept terms of service" checkbox (called agreement) on a form. The app is using Devise for the user management.

views/devise/registrations/new.html.erb has:

<%= f.check_box :agreement, class: 'form-control' %>

The application_controller.rb has:

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:agreement, :phone, :first_name, :last_name, :domain, :email, :password, :password_confirmation) }
  end

Then in the user.rb controller, it has

# neither of the below worked
# validates :agreement, :acceptance => true
validates :agreement, acceptance: true

If I view the data in the development.log, it shows the agreement field coming through correctly with a value of 1, which is (according to the Rails docs, the expected value for the validation):

Parameters: {"utf8"=>"✓", "authenticity_token"=>"jFg6+ZDM1qldh020lv/FQHxlgZkby2dhUbejjXurr4w=", "user"=>{"first_name"=>"Joe", "last_name"=>"Smith", "phone"=>"2098993344", "domain"=>"google.com", "email"=>"[email protected]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "agreement"=>"1"}, "commit"=>"Create User"} 

However, any time the form is submitted it shows an error message that "Agreement must be accepted", whether it's checked or not.

Any ideas on what this is caused by?

like image 705
user101289 Avatar asked Mar 19 '23 17:03

user101289


1 Answers

Try using this for your validation

validates :agreement, acceptance: { accept: true }

as per the Rails documentation

:accept - Specifies value that is considered accepted. The default value is a string “1”, which makes it easy to relate to an HTML checkbox. This should be set to true if you are validating a database column, since the attribute is typecast from “1” to true before validation.

like image 152
Brandon Cordell Avatar answered Apr 07 '23 07:04

Brandon Cordell