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

馋奶兔 提交于 2019-12-01 01:00:25
BJ Clark

<%= check_box_tag "todo_ids[]", todo.id, false, :id => "todo_id_#{todo.id}" -%> or whatever you want the id to be.

I consider this a bug with check_box_tag caused by the seemingly hackish nature of manually giving it the name todo_ids[] and the method code calling sanitize_to_id(name). I just ran into this yesterday and I'm contemplating a patch.

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[#{todo.id}]", todo.id %>

In the action called by the form:

Todo.update_all(["completed_at = ?", Time.now], :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"}

Can you try this and let us know if it works:

check_box_tag "todo_ids[#{todo.id}]", todo.id %>

This is the expected behaviour of check_box_tag, as this comment on a rejected fix explains.

You can use collection_check_boxes like this (haml syntax, sorry):

# Accumulate todos in a params hash like { todos: { to_complete: [] } }
= collection_check_boxes(:todos, :to_complete, @incomplete_todos, :id, :name) do |todo_builder|
  = todo_builder.label do
    # This is the result of calling :name on the todo, as specified
    # calling the helper
    = todo_builder.text
    = todo_builder.check_box

Of course you can use partials inside the block, just pass and use the builder inside.

Check more options in the API docs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!