我已经按照说明中的说明建立了一个轨道形式 这个 铁路广播。

这是表格的代码:

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

这是待办事项的代码:

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

它运行良好,但是我希望开始实现Ajax,我需要每个复选框才能具有唯一的ID。现在,生成的输入标签看起来像这样:

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

每个复选框都具有相同的ID(“ todo_ids_”),这是一个问题。我怀疑该解决方案很简单,但我没有看到它。有小费吗?

有帮助吗?

解决方案 2

我最终使用了类似于瑞安(Ryan)的解决方案,但是正如我在评论中所写的那样,我必须做出进一步的更改。以形式:

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

在表格中调用的动作中:

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

请注意最后的“ params [:todo_ids] .keys”,这是处理参数格式化的奇数方式的解决方法:

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

其他提示

<%= check_box_tag "todo_ids[]", todo.id, false, :id => "todo_id_#{todo.id}" -%> 或您想要ID的任何东西。

我认为这是一个带有check_box_tag的错误,这是由手动命名为todo_ids []和调用sanitize_to_id(name)的方法代码而引起的。我昨天遇到了这一点,我正在考虑一个补丁。

您可以尝试一下,让我们知道它是否有效:

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

这是预期的行为 check_box_tag, , 作为 关于拒绝修复的评论解释了.

您可以使用 collection_check_boxes 像这样 (哈姆尔 语法,对不起):

# 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

当然,您可以在块内使用部分,只需通过并在内部使用构建器即可。

检查更多选项 API文档.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top