Thursday, September 17, 2009

Rails and Disabled Checkboxes

If you have a disabled checkbox in a Rails form and save that form, the field will be saved as false, unless readonly on that field is set to true, in which case the value of the field will be perserved. So, if you want discourage the user from unchecking the Terms and Conditions after they'd already agreed to them earlier and saved the form, you can do something like this:
<% unless @user.accepted_terms_and_conditions %>
  <%= f.check_box :accepted_terms_and_conditions %>
<% else %>
  <%# User checked it previously and saved form, so we disable it to indicate that they cannot undo this. Note that it must be readonly. %>
  <%= f.check_box :accepted_terms_and_conditions, :disabled => true, :readonly => true %>
<% end %>

No comments: