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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With