Rails 怎样构造这样的表单?

Peter · September 09, 2015 · Last by haisong replied at September 09, 2015 · 2277 hits

截图是 phpMyAdmin 的:

实际实用就是一个用户列表,多选或全选后,点击删除按钮,然后传到 controller 去, 简单来说可以用下面的方法实现,我想知道有没有可能用 simple_form 的 gem 实现?或者 form_for 也可以啊。

谢谢

<form method="POST" action="some_url">
<table>
  <thead>
    <tr>
      <th> </th>
      <th>Username</th>
    </tr>
  </thead>

  <tbody>
  <% @users.each do |user| %>
  <tr>
    <td><input name="user_ids[<%= user.id %>]" type="checkbox" value="<%= user.id %>"/></td>
    <td><%= user.name %></td>
  </tr>
  <% end %>
  </tbody>
</table>
<input type="submit" name="delete" value="删除用户"/>
</form>

这样就可以吧,name 以空括号结尾的会处理为数组

<% @users.each do |user| %>
<tr>

  <td><input name="user_ids[]" type="checkbox" value="<%= user.id %>"/></td>

  <td><%= user.name %></td>
</tr>
<% end %>

或者用 helper 方法 collection_check_boxes

<%= form_for @post do |f| %>
  <%= f.collection_check_boxes :author_ids, Author.all, :id, :name_with_initial %>
  <%= f.submit %>
<% end %>
You need to Sign in before reply, if you don't have an account, please Sign up first.