2

I have a checkbox

<%= f.check_box :anonymous %>

And my table has a column anonymous which is true or false.

Code generated in html:

 <input name="comment[anonymous]" type="hidden" value="0" />
 <input id="comment_anonymous" name="comment[anonymous]" type="checkbox" value="1" />

Now, for some reason when I add data it's not saving if my anonymous checkbox is checked or not.. it's not changing data in database.. All other fields gets saved except anonymous.

What can be the problem ?

2
  • Can you show more of the view code? Like the form_for around the f.check_box? Commented Oct 9, 2013 at 16:20
  • <%= form_for(comment, :url => (defined?(submit_url) ? submit_url : [commentable, "comments"]), :method => :post, :id => "comment-form", :class => "form-horizontal") do |f| %> Commented Oct 9, 2013 at 16:24

1 Answer 1

1

Use #check_box_tag instead:

<%= check_box_tag(:anonymous) %>

From the official guides:

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I am getting: 'undefined method check_box_tag' for #<ActionView::Helpers::FormBuilder:0xc921828>'`
@user1736479 I guess that you did ` f.check_box_tag`. Look at my proposed solution again :)
Agis, I tried your solution and it's not working. I am still getting only false into my database. I am opening tag like that: <%= check_box_tag :anonymous, 1, false, data: { "label" => "Želim ostati anonimen" } %>
I've found another bug, my initial checkbox is working right, but I am also using github.com/arthurgouveia/prettyCheckable plugin for my checkboxes and it seems to be making problem.. Any idea ?
Well that is another subject and unfortunately I can't help you with this. But if you deactivate it and everything works then you're OK :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.