Grant Heaslip Grant Heaslip - 5 months ago 20
Ajax Question

How do I set a unique ID for checkboxes in a multi-record Rails form?

I've set up a Rails form roughly following the instructions in this Railscast.

Here's the code for the form:

<% form_tag complete_todos_path, :method => :put do %>
<div id="incomplete_todos">
<% @incomplete_todos.each do |todo| %>
<%= render :partial => todo %>
<% end %>
<%= submit_tag "Mark as completed" %>
<% end %>

And here's the code for the todo partial:

<div class="todo">
<%= check_box_tag "todo_ids[]", %>
<%=h %>
<%= link_to 'edit', edit_todo_path(todo) %>
<%= link_to 'delete', todo, :confirm => 'Are you sure?', :method => :delete %>

It's working great, but I'm looking to start implementing AJAX and I need each checkbox to have a unique id. Right now, the input tags generated look something like this:

<input id="todo_ids_" name="todo_ids[]" type="checkbox" value="7" />

Every check box has the same id ("todo_ids_"), which is a problem. I suspect the solution is embarrassingly simple, but I'm not seeing it. Any tips?


I ended up using a solution similar to Ryan's, but as I wrote in the comment I had to make a further change. In the form:

<%= check_box_tag "todo_ids[#{}]", %>

In the action called by the form:

Todo.update_all(["completed_at = ?",], :id => params[:todo_ids].keys)

Note the "params[:todo_ids].keys" at the end, which was a workaround to deal with the odd way the parameters were formatted:

"todo_ids" => {"5"=>"5"}