Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in rails, What is the value returned in for a checkbox?

I want to set a cookie to expire in 1 year if the 'remember me' checkbox is checked.

I have a checkbox form input like:

<%= check_box_tag 'remember', '', false, :class => 'checkbox' %>

What will the value be when it gets posted?

Will it be true/false or checked or 1 or? I set the value to '' in the helper.

like image 814
Blankman Avatar asked Oct 31 '10 21:10

Blankman


2 Answers

Checkbox will return either 0 or 1.

Don't compare with false and true, as this may cause you problems, since 0 is true in Ruby.

like image 93
chech Avatar answered Nov 15 '22 09:11

chech


In the rails API documentation it has this helpful explanation of missing parameters and the hidden field work-around:

http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-check_box

check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")

Returns a checkbox tag tailored for accessing a specified attribute (identified by method) on an object assigned to the template (identified by object). This object must be an instance object (@object) and not a local object. It’s intended that method returns an integer and if that integer is above zero, then the checkbox is checked. Additional options on the input tag can be passed as a hash with options. The checked_value defaults to 1 while the default unchecked_value is set to 0 which is convenient for boolean values. Gotcha

The HTML specification says unchecked check boxes are not successful, and thus web browsers do not send them. Unfortunately this introduces a gotcha: if an Invoice model has a paid flag, and in the form that edits a paid invoice the user unchecks its check box, no paid parameter is sent. So, any mass-assignment idiom like

@invoice.update_attributes(params[:invoice])

wouldn’t update the flag.

To prevent this the helper generates an auxiliary hidden field before the very check box. The hidden field has the same name and its attributes mimic an unchecked check box.

This way, the client either sends only the hidden field (representing the check box is unchecked), or both fields. Since the HTML specification says key/value pairs have to be sent in the same order they appear in the form, and parameters extraction gets the last occurrence of any repeated key in the query string, that works for ordinary forms.

like image 24
earnold Avatar answered Nov 15 '22 08:11

earnold