[Rails] Multiple checkboxes

Hampton
Mon, 05 Jun 2006 01:19:31 -0000

Your problem is probably because of what you set "value" to be.

I think if you exam your params <%= debug params %> you will see that the
option is returning the value that you are setting its ''checked
value'' to.

Secondly, if there were 15 check boxes, they are all named the same thing,
so as far as my understanding goes, each checkbox will overwrite itself.

May I recommend this in your view?

<%= form_tag :action=>''save_question''%>
<%= @question.title %>

 <% for option in @options %>
 <input type="checkbox" name="option[<%= option.id
%>]" value="1"><%option.option_text %>
 <% end %>

 <%= submit_tag%>
<%= end_form_tag%>

Then your controller can do this...

 @options = Option.find_all_by_question_id(session[:question_id])
 response = ""
 for option in @options do
    response << params[:options][option.id.to_s]
 end
end

Haven''t tested this code, but it should work.

-hampton.

On 6/4/06, Martin Robinson <martinr@4elements.co.uk>
wrote:
>
> Please could someone suggest what might be wrong here. In my view
I''m
> displaying a series of check boxes and when the form is submitted I want
> the controller to iterate over the values and contatenate them all  into
> a string "1" if the box was checked and "0" if it
wasn''t.
> I''m new to Ruby and Rails and I can''t seem to get any
values out of my
> params other than "0",
>
> Here''s my code:
>
>
> View:
>
>
> <%= form_tag :action=>''save_question''%>
> <%= @question.title %>
>
>   <% for option in @options %>
>   <input type="checkbox" name="option[]"
value="<%=option.id%>"><%> option.option_text
%>
>   <% end %>
>
>   <%= submit_tag%>
> <%= end_form_tag%>
>
>
>
> Controller:
>
> def save_question
>
> @options = Option.find_all_by_question_id(session[:question_id])
> response = ""
> for option in @options do
>    if params[:option][option.id]=="1"
>      response << "1"
>    else
>      response << "0"
>    end
> end
> end
>
>
> --
> Posted via http://www.ruby-forum.com/.
> _______________________________________________
> Rails mailing list
> Rails@lists.rubyonrails.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
>
-------------- next part --------------
An HTML attachment was scrubbed...