Search code examples
ruby-on-railsrubyhaml

Checkbox in Rails has three values which is causing issues


I'm new to Rails.

I have a situation where we have a fairly important form that we can't default answers for users as it revolves around government tax authorisation related things so our boolean answers essentially have three states:

nil -> user hasn't provided an answer
true -> User has said true
false -> User has said false

The issue I'm having in our Rails backend with this is by default the form.check_box :some_proper is defaulting the input to false when if the value is nil it needs to remain nil.

So what's happening is a whole series of nil values are changing to false when our form is submitted.

I have provided some code examples, but I can't find anyway of doing what's needed and we may just need to swap from checkboxes to select fields or something.

%dt= form.label :knowledge_intensive
%dd= form.check_box(:knowledge_intensive, {}, "1", "0")

I have attached a GIF to illustrate the issue clearer:

Demo of issue in GIF Form


Solution

  • The form builder adds a hidden field with the same name as your knowledge_intensive field. If you inspect the generated HTML it will appear immediately before the input for the checkbox.

    The reason for this is to allow an unchecked box to pass through as false. I'm not sure how you can get around this, as this mechanism is required to pass the state as a param (HTML spec implies unchecked checkboxes aren't passed as form params). There's no easy way to have separate nil/true/false values - you are probably better off using radio buttons for that.

    But that's the reason. The auxiliary hidden field is has a value of '0' and that will be interpreted as 'false' by Rails, unless the user checks the check box.

    Does that make sense?