How to get parameters from a checkbox in rails3 controllers

Here are my codes:

<%=form_tag('/user_group_follows/follow',:id=>'follow_select_form',:remote=>true,:method=>:get) do %>
    <p>You want to add this user to?</p>
    <%=hidden_field_tag 'user_id',>
    <%@user.user_groups.each do |ug|%>
        <%=check_box_tag 'user_group_id',,false,{:id=>'user_group_id_'}%><><br/>
//using jquery-ui, so there is no submit button....


I want the user to make multiple selections to decide which groups he or she would like to add to the next list.

So, I made several checkboxes with the same name as "user_group_id" and different IDs. I could successfully get params throught params [: user_group_id] if the user has only completed one checkbox. But if he actually checked several of them, how do I set this value in the controller? In this case, parameters [: user_group_id] can only receive one of them. And I'm pretty sure codes like: params [: user_group_id_ +] aren't going to work ....


source to share

2 answers

If you call them a type id user_group_id['']

, I think you should get parameters like params[:user_group_id]

, which should contain an array of all the IDs of the checked groups.

Something like this is not entirely accurate, but basically you want to name your fields so that they are grouped into an array in a natural way, due to the way they are called:

<%=check_box_tag 'user_group_id['']',,false,{:id=>'user_group_id_'}%><>


So params[:user_group_id].first

will contain the ID of the first checkbox that was selected.



if you go this way <% = check_box_tag 'user_group_id []'%> it returns an array of the selected ids,

<%=check_box_tag 'user_group_id',, params[:user_group_id].try(:include?,,{:id=>'user_group_id_'}%>




All Articles