如何为多记录Rails表单中的复选框设置唯一ID? [英] How do I set a unique ID for checkboxes in a multi-record Rails form?

查看:134
本文介绍了如何为多记录Rails表单中的复选框设置唯一ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已大致按照中的说明设置了Rails表单> Railscast。

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

以下是表单的代码:

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

这里是todo partial的代码:

And here's the code for the todo partial:

<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。现在,生成的输入标签看起来像这样:

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" />

每个复选框都有相同的id(todo_ids_),这是一个问题。我怀疑解决方案是尴尬简单,但我没有看到它。任何提示?

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?

推荐答案

我最终使用了一个类似于Ryan的解决方案,但正如我在评论中写道,进一步改变。格式为:

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)

注意在末尾的params [:todo_ids] .keys,这是一个解决方法来处理参数格式化的奇怪方式: / p>

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"}

这篇关于如何为多记录Rails表单中的复选框设置唯一ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆