user1738017
user1738017

Reputation: 627

Checkbox not staying checked in rails form

I have this in part of my form_tag

%input{ :type => "checkbox", :name => "form", :value => "#{@t.form}"}

It saves to the database as 1 when i check it the first time, but then if i navigate back to the form it doesn't show up checked..

Upvotes: 4

Views: 2633

Answers (1)

Manoj Monga
Manoj Monga

Reputation: 3083

Firstly, this is not a recommended way to add the form and fields in rails. But, still to answer you question, you can go with this:

%input{ :type => "checkbox", :name => "form", :value => true, :checked => @t.form ? "checked" : ""}

Notice that I have changed the value part to true as it is the value attribute of the checkbox that will always have the same value.

Now there would be another problem, if the checkbox was previously checked and now you are unchecking it and saving the form then it will not save the value "0" of false in database.

According to the HTML specification unchecked checkboxes submit no value. However it is often convenient for a checkbox to always submit a value.

Now to avoid this problem, you need to add a hidden field as well.

%input{ :type => "hidden", :name => "form", :value => false}
%input{ :type => "checkbox", :name => "form", :value => true, :checked => @t.form ? "checked" : ""}

Now, 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.

Note: I will recommend you to use rails methods for generating hidden fields and checkbox.

Update(with form_tag helpers)

= hidden_field_tag('form', '0')
= check_box_tag("form", '1', @t.form)

I think you are using HAML and the form is a boolean field in database.

Upvotes: 1

Related Questions