如何为Rails 3.2索引页中的每一行添加一个复选框? [英] How to add a checkbox for each row in Rails 3.2 index page?

查看:87
本文介绍了如何为Rails 3.2索引页中的每一行添加一个复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们想在Rails索引页面上为每一行添加一个复选框,以标记该行。此复选框不是对象的一部分(数据库中没有checkbox布尔)。当索引页显示时,用户可以选中该框以在以下过程中触发该行的事件:

We would like to add a checkbox to each row on Rails index page to flag for the row. This checkbox is not part of the object (no checkbox boolean in database). When the index page shows, a user can check the box to trigger an event for the row in following process:

#objects/checkbox_index.html.erb    
<table>
  <tr>
    <th>CheckBox</th>
    <th>Object Name</th>
    <th>Object ID</th>
  </tr>
  <%= @objects.each do |obj| %>
    <tr>
      <td><%= checkbox %></td>
      <td><%= obj.name %></td>
      <td><%= obj.id %></td>
    </tr>
  <% end %>
</table>

在控制器中,过程将如下所示:

In controller, the process will be like this:

@objects.each do |obj|
  some_event if obj.checked
end

有几个问题不太明白:

1. How to declare an array checkbox variable on the form and link it to each row of obj? We have been using `attr_accessor` to declare var for a form. 
2. How to retrieve each row on checkbox_index form and pass them back to controller?  We are using simple_form for new/edit. 

任何人都可以指出这种行为的任何好例子,或者建议我们应该考虑什么关于?非常感谢。

Can anyone point me towards any good examples of this sort of behavior, or suggest what we should be thinking about? Many Thanks.

推荐答案

一个解决方案是将一个Javascript事件侦听器添加到不是表单的一部分的复选框。如果你想要触发的动作是一个数据库调用,你可以用ajax来做。没有坐下和写所有的JavaScript代码,Ruby和伪JavaScript代码可能看起来像这样:

One solution to this would be to add a Javascript event listener to a checkbox that is not part of the form. If the action you want triggered is a database call, you can do that with ajax. Without sitting down and writing all of that javascript code, the Ruby and pseudo javascript code might look something like this:

Ruby

<% @objects.each do |obj| %>
    <%= check_box_tag, class: "checkbox" %>
<% end %>

Javascript / JQuery

$('#checkbox').on change {
    if selected == selected
        do what you are trying to do on $(this).element (like an ajax call)
    else
        undo what you did
    end
}

这篇关于如何为Rails 3.2索引页中的每一行添加一个复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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