Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails, how to handle multiple checked checkboxes, just split on the , or?

Curious what the 'rails way' of handling the situation when a user checks multiple checkboxes (with the same name value), and it gets posted back to the controller.

How would you check if multiple items were selected, then splitted on the ID values etc.

like image 481
Blankman Avatar asked Dec 13 '10 01:12

Blankman


2 Answers

The easiest way of doing this is to set those checkboxes up to become an array.

HTML:

<input type="checkbox" name="tag_ids[]" value="1" /> <input type="checkbox" name="tag_ids[]" value="2" /> <input type="checkbox" name="tag_ids[]" value="3" /> 

Controller:

tag_ids = params[:tag_ids] 

(Of course, you'd probably be using form_for-based helpers in the view, and therefore mass-assigning the tag IDs. This is just the most generic example.)

like image 50
Matchu Avatar answered Oct 05 '22 06:10

Matchu


f.check_box :tag_ids, {multiple: true}, 1, nil 

Is the right answer:

Here is the reason, there is a 'multiple: true' option that allows your input to be placed in an array. If there isn't a multiple: true option this will not be allowed.

like image 25
FlyingV Avatar answered Oct 05 '22 06:10

FlyingV