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.
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.
Not the most elegant solution, but you could do something like the following:
Add these methods to your user model:
def privacy_enabled=(val)
self.privacy_disabled = val == "0"
end
def privacy_enabled
!privacy_disabled
end
Change the form to:
<%= form.check_box :privacy_enabled %>
Again, not elegant, but it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With