Multiple select of checkboxes
This is Rails related. I am not sure why this was not covered in any of Rails-related manuals, tutorials or API documents. Maybe it is, somewhere out there in the wild, but it sure took me a long time to figure this one out. A chance analysis of sample code, remotely related to a checkbox, by another person crying for help because his code was not working, gave me a lead in how to get this working.
So if you are trying to do a multiple select of checkboxes in your form, but when you submit the form, only one value was available in your controller, then here’s the solution.
In your rhtml file, your checkbox code should be:
<%= check_box_tag ‘item[]’, item.value%>
Note the “item[]”. This will become the checkbox’s value name. But it’s the [] that will be interpreted into an Array type, and the selected values populated into an Array. The “item.value” is to be replaced by whatever value you intend to put in.
At your controller, you can retrieve the array of values by:
values = params[items]
There you have it. Multiple select of checkboxes. 🙂
This worked great, thank you!
One question – when building an ‘Edit’ view, how would I tell the checkboxes to be checked or not based on the data retrieved from the database? I’ve stored the checked values as a serialized array.
Hi Justin,
Glad to hear that it worked for you. 🙂
check_box_tag has a ‘checked’ option. Just include the ‘checked => true’ if you want that check box to be checked. You can see the api doc here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#M000610
So my guess is that your code will look something like this:
myarray.include?(item.value) %>
Yes, in the second version of Agile Web Development with Rails, the check_box information even became MORE sparse!!
This might also help:
http://wiki.rubyonrails.com/rails/pages/CheckboxHABTM
so easy, so helpful! thanks a lot
Hey, that is great! It wasn’t easy for me until I saw your solution to this problem. But, now, I am dealing with a similar yet different problem of sending an array as a parameter to the rendering action. Basically, this is what I want to do:
render :action => ‘some_action’, :parameter => @myData
where @myData is a simple array of strings. But, I am unable to perform such an action because, the GET tells me that the receiver only gets the first value from the array. Your input will be greatly appreciated.
please help me
i am using checkbox for every item in a loop of items,in that when i am selecting some items by check box and when i click on the add button these selected items should be displayed in new page. so how can i pass the checkbox array to controller