Forum: Ruby on Rails check_box

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community 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:

RHTML:
<% for book in @books do %>
  <tr>
    <td><%=book.label%></td>
    <td>
      <%checked = book.subscribed ? 'checked': 'nope'%>
      <%=check_box("book" + book.id.to_s, 'checked', :checked =>
checked)%>
    </td>
  </tr>
<% end %>

RB:
params["book" + book.id.to_s]['checked']

**
I would much rather have something like this in the RHTML:
<% for book in @books do %>
  <tr>
    <td><%=book.label%></td>
    <td>
      <%=check_box('book', 'subscribed')%>
    </td>
  </tr>
<% 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[' + book.id.to_s + '][subscribed]', 'whatever',
book.subscribed)

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)
Jim,

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...

HTH,
Dan
This topic is locked and can not be replied to.