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.id%>
    <%@user.user_groups.each do |ug|%>
        <%=check_box_tag 'user_group_id',ug.id,false,{:id=>'user_group_id_'+ug.id.to_s}%><%=ug.name%><br/>
    <%end%>
<%end%>
//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_ + XXX.id] aren't going to work ....

+3


source to share


2 answers


If you call them a type id user_group_id['+ug.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['+ug.id']',ug.id,false,{:id=>'user_group_id_'+ug.id.to_s}%><%=ug.name%>

      

So params[:user_group_id].first

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

+5


source


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',ug.id, params[:user_group_id].try(:include?,ug.id.to_s),{:id=>'user_group_id_'+ug.id.to_s}%>

      

0


source







All Articles