views:

26

answers:

2

I've got a form_for form, and within it, I'm using a form helper check box. The model has a field that's a boolean value, but I'd like to be able to display it on my form in terms of its converse since I think that's easier for users to understand.

Is there any way for me to have a Rails form helper act as if the model's boolean field is flipped?

Example:

<% form_for :user do |form| %>
  <%= form.check_box :privacy_disabled %>
<% end %>

In this example, the User model has a boolean field privacy_disabled. I would like to display this in the form as check here to enable privacy.

The checkbox helper function has the ability to set its checked and unchecked values, but inverting these does not seem to properly populate the checkbox with the pre-saved value.

+1  A: 

Not the most elegant solution, but you could do something like the following:

  1. Add these methods to your user model:

    def privacy_enabled=(val)
      self.privacy_disabled = val == "0"
    end
    def privacy_enabled
      !privacy_disabled
    end
    
  2. Change the form to:

    <%= form.check_box :privacy_enabled %>
    

Again, not elegant, but it works.

vegetables
A: 

This is how I ended up solving this issue, I was actually close with my first attempt:

<%= form.check_box :privacy_disabled, 
                   {:checked => [email protected]_disabled}, 
                   0,
                   1 %>

So the values returned by the checkbox are flipped, and whether it starts out checked is manually flipped as well.

WIlliam Jones