Ruby on Rails: use form_for for the model and flip the form value

I have a form_for form, and inside it I use the helper flag. The model has a field that is a boolean, but I would like to be able to display it in my form from the point of view of its opposite, since I think it is easier for users to understand.

Do I have a way for the Rails form helper to act as if the Boolean field of the model were upside down?

Example:

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

In this example, the user model has a logical field privacy_disabled. I would like to show it in a form, like here, to enable privacy.

The flag helper function has the ability to set its checked and unverified values, but inverting them does not seem to fill the flag with the previously saved value.

+5
2

, :

<%= form.check_box :privacy_disabled, 
                   {:checked => !@user.privacy_disabled}, 
                   0,
                   1 %>

, , , , , .

+9

, - :

  • :

    def privacy_enabled=(val)
      self.privacy_disabled = val == "0"
    end
    def privacy_enabled
      !privacy_disabled
    end
    
  • :

    <%= form.check_box :privacy_enabled %>
    

, , .

+6

All Articles