Using check_box

If I wish to create a set of checkboxs based on the rows of a table in
my database would I have to loop through each row of the database using
a for loop? or can I just use the check box method once and pass it an
array of values?

Stewart M. wrote:

If I wish to create a set of checkboxs based on the rows of a table in
my database would I have to loop through each row of the database using
a for loop? or can I just use the check box method once and pass it an
array of values?

I’m not sure if there is an existing helper. I generally use a loop:

<% @categories.each do |category| %>
<%= check_box_tag(“product[category_ids][]”,
category.id,
@product.categories.include?(category)) %>
<%= category.name %>

<% end %>

The above code demonstrates the assigning of categories to products in a
has and belongs to many relationship.

This could easily be extracted into a helper for use throughout your
application.

There are a few plugins related to checkboxes and other form helper -
you could either use those or take a look at the source for inspiration
for your own code:
http://www.agilewebdevelopment.com/plugins/search?search=checkbox

Hope that helps,

Steve

Hi Stewart,

Stewart M. wrote:

If I wish to create a set of checkboxs based on
the rows of a table in my database would I have
to loop through each row of the database using
a for loop? or can I just use the check box method
once and pass it an array of values?

Each checkbox has to be rendered individually.

Bill W. wrote:

Hi Stewart,

Stewart M. wrote:

If I wish to create a set of checkboxs based on
the rows of a table in my database would I have
to loop through each row of the database using
a for loop? or can I just use the check box method
once and pass it an array of values?

Each checkbox has to be rendered individually.

Thanks for that Bill just needed to know the best way to do it.

I am going to try Stephen’s code now Thanks a lot guys!