In my Rails 3.2 app, I have a signup form that includes a “terms and conditions” checkbox. The form looks something like this:
<%= form_for @user do |f| %>
<!-- Error message stuff -->
<%= f.text_field :email %>
<!-- More fields... -->
<%= text_field_tag :terms_and_conditions, false, "true" %>
<% end %>
To make sure the user checks that checkbox, I have the following code in my controller:
unless params[:terms_and_conditions] == "true"
@user.errors[:base] << "You must check the 'Terms and Conditions' checkbox"
end
But when I call @user.save (or @user.valid?), it seems to clear out this error message. I know I could use @user.errors.empty? && @user.save, but I find it strange that the save method doesn’t care about the error message I just added. Is there a better and more elegant way to do this?
Rails offers an acceptance validator. It’s perfect for your situation. See docs for further information.