3

Here is 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 wanna the user to make a multiple choice to decide which groups that he/she would like to add into the following list.

So I made several checkboxes with the same name as 'user_group_id' and different ids. I could successfully get the params throught params[:user_group_id], if the user only checked one box. But if he truly checked several of them, how to get this value set in controller? In this circumstance, params[:user_group_id] could only get one of them. And I quite believe codes like: params[:user_group_id_+XXX.id] is not going to work....

0

2 Answers 2

5

If you name them with id's like user_group_id['+ug.id+'], I think you should get params like params[:user_group_id] which should contain an array of all the id's of groups that were checked.

Something like this, not sure exactly, but basically you want to name your fields such that they are grouped into an array naturally, by virtue of how they are named:

<%=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 would contain the id of the first checkbox that was selected.

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

2 Comments

em...I think it is not working, params[:user_group_id].first only returns 1, but actually the expected user_group_id should be 28 and 29...
Well, I have got it, the codes should be: <%=check_box_tag 'user_group_id[]'%> so that the Rails will recognize params[:user_group_id]as an array! Thanks anyway, your answer really did a great hint!
0

if you go in this way <%=check_box_tag 'user_group_id[]'%> it's returning array of 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}%>

Comments

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.