Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Use form_for on a model, and flip the form value

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.

like image 832
William Jones Avatar asked Aug 19 '10 23:08

William Jones


2 Answers

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.

like image 52
William Jones Avatar answered Oct 21 '22 05:10

William Jones


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.

like image 40
venables Avatar answered Oct 21 '22 03:10

venables