Forum: Ruby on Rails check_box

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Jim H. (Guest)
on 2006-04-18 08:10
(Received via mailing list)
I've got a question on the use of check_box.

This is working but there just has to be a better way:

<% for book in @books do %>
      <%checked = book.subscribed ? 'checked': 'nope'%>
      <%=check_box("book" +, 'checked', :checked =>
<% end %>

params["book" +]['checked']

I would much rather have something like this in the RHTML:
<% for book in @books do %>
      <%=check_box('book', 'subscribed')%>
<% end %>

The issue I run into though is that the naming convention ends up
being the same for all of my books (since I am referring to them as
"book" when the check_box is created.

something like: <%=check_box('book.label', 'subscribed'%> results in
errors as well...

Like I said, the first block if working for me but... let me know of
any alternatives.

Thanks in advance
- Jim
Daniel H. (Guest)
on 2006-04-18 08:28
(Received via mailing list)
I would do something like

check_box_tag('books[' + + '][subscribed]', 'whatever',

But I'm relatively new so that might not be the best way.

This will results in hash that looks like

params[:books][0][:subscribed] => 'whatever'

if checked
Dan S. (Guest)
on 2006-04-18 08:50
(Received via mailing list)

You can pass an :index parameter to the check_box method (and
text_field, and probably a few others) like this:

check_box :mycollection, :available, :index => "1"

which outputs html like this:

<input id="mycollection_1_available" name="mycollection[1][available]"
type="checkbox" value="1" />

So you can easily iterate through this just by getting the indexes you
expect on the other side. Remember that the index will always be a
string in the params hash though...

This topic is locked and can not be replied to.