1

I'm trying to have an if else statement in the controller to do something if the check_box_tag is checked and something else if it isn't checked.

<%= check_box_tag "apply[]", 1, false %>

If it is checked and the form is submitted "apply"=>["1"] is passed as a parameter, if it isn't checked nothing is sent.

Can I have a "apply"=>["0"] passed as a param if it isn't checked?

Rob
  • 1,835
  • 2
  • 25
  • 53

2 Answers2

2

The check_box_tag indeed does not use the hidden field so it does not send anything in case the box is unchecked (unlike the check_box helper, which is nevertheless still not useful in case of an array param, as Meier notes above).

If you are trying to use your checkbox in a similar way as in this SO question (i.e. to send a user-selected array of ids for example), the simple solution might be to react on an empty param in the controller. Something in the way of:

params[:apply] ||= []

If, on the other hand, you wanted to use the checkboxes as an ordered array where each value would be determined by its constant position in the array, either true or false, (i.e. if you wanted to get something like this in the apply param: [0, 1, 0, 0, 1]), this wouldn't work. You'd have to choose a different approach, e.g. use the checkboxes with a hash param instead of array.

Community
  • 1
  • 1
Matouš Borák
  • 15,606
  • 1
  • 42
  • 53
0

The rails guide has a warning box about this special case:

http://guides.rubyonrails.org/form_helpers.html

Array parameters do not play well with the check_box helper. According to the HTML specification unchecked checkboxes submit no value.

However it is often convenient for a checkbox to always submit a value. The check_box helper fakes this by creating an auxiliary hidden input with the same name. If the checkbox is unchecked only the hidden input is submitted and if it is checked then both are submitted but the value submitted by the checkbox takes precedence. When working with array parameters this duplicate submission will confuse Rails since duplicate input names are how it decides when to start a new array element. It is preferable to either use check_box_tag or to use hashes instead of arrays.

Meier
  • 3,858
  • 1
  • 17
  • 46
  • This line confuses me 'It is preferable to either use check_box_tag or to use hashes instead of arrays.' I feel like its saying it is preferable to use `check_box_tag` because it will send a param for both checked and un checked. But it doesn't... – Rob Mar 06 '16 at 00:50