[Rails] Re: Multiple checkboxes

Hampton
Tue, 06 Jun 2006 12:18:44 -0000

Actually, I believe the helper works like this.

<input type="checkbox" name="option[<%= option.id
%>]" value="1">
<input type="hidden" name="option[<%= option.id
%>]" value="0">
<%= option.option_text %>

That should return a 0 value if unchecked.

-hampton.

On 6/5/06, Martin Robinson <martinr@4elements.co.uk>
wrote:
> Hampton wrote:
> > 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.
>
> Thanks for that - I''ve got it working now. i took your
suggestions, but
> for some reason if a checkbox isn''t checked a value
doesn''t get returned
> so if I use the code
>
> >  for option in @options do
> >     response << params[:options][option.id.to_s]
> >  end
>
> I get a nil object error for unchecked checkboxes.
>
> The actual code I got working is
>
>   for option in @options do
>     if params[:option][option.id.to_s]=="1"
>      response << params[:option][option.id.to_s]
>     else
>      response << "0"
>     end
>   end
>
> and the view code worked just as you said.