Rails 4,为表中的每个对象添加复选框?

时间:2016-08-02 17:56:29

标签: ruby-on-rails forms loops checkbox html-table

我想有条件地为表中的每个对象添加一个复选框,这样用户就可以选择多个项目。当用户单击提交时 - 我想更改所选对象的状态并通过ajax更新表。我看了看 collection_check_boxes但我不确定如何在这种情况下实施它。

见下面,我想修改的代码 - 包括每行的复选框。

<% if @events != nil %>
    <% @events.each do |event| %>
    <tr>
        <td><%= event.driver.name%></td>
        <td><%= event.name%></td>
        <td><%= event.drop_off? ? "Drop Off At" : "Pick Up From" %></td>
        <td><%= event.location_name%></td>
        <td><%= event.is_game ? "Game" : "Not Game(event, practice)" %></td>
        <td><%= event.location_address %></td>
        <td><%= event.date ? event.date.strftime("%A, %d %b %Y %l:%M %p") : "Please Enter Details on TeamSnap!"%></td>
    </tr>
    <% end %>
<% end %>

更新:

这就是我提出的:

<% if @events != nil %>
    <%= form_tag events_swap_path(@carpool) do %>
        <div><%= submit_tag 'Swap!' %></div>
        <% @events.each do |event| %>
        <tr>
            <td><%= event.driver.name%></td>
            <td><%= event.name%></td>
            <td><%= event.drop_off? ? "Drop Off At" : "Pick Up From" %></td>
            <td><%= event.location_name%></td>
            <td><%= event.is_game ? "Game" : "Not Game(event, practice)" %></td>
            <td><%= event.location_address %></td>
            <td><%= event.date ? event.date.strftime("%A, %d %b %Y %l:%M %p") : "Please Enter Details on TeamSnap!"%></td>
            <td><%= fields_for "events[]", event do |f| %>
                        <%= f.check_box :id, {multiple: true}, 1, nil %>
                    <% end %>
            </td>
        </tr>
        <% end %>
    <% end %>
<% end %>

问题是,当我提交时,我在params哈希中为我选择的事件获得了一个不受欢迎的哈希结构。在下面提交后查看params散列中的内容:

{"commit"=>"Swap!", "utf8"=>"✓", "authenticity_token"=>"P0JNhyco3B5ijMFurf3SIQ9ILTT9CGUyrmdInoshwPWvyF+E/xoWbEKH7ubN30EwIOjKQw1rwC3Vv8ZCgaMoKQ==", "events"=>{"869"=>{"id"=>["1"]}, "870"=>{"id"=>["1"]}}, "controller"=>"events", "action"=>"swap", "carpool_id"=>"8"}

理想情况下,我会得到类似的东西。

events => {"id"=>"869", "id"=>"870"}

因此,我可以轻松遍历选定的事件列表并提取所有事件ID。

1 个答案:

答案 0 :(得分:0)

解决方案:

SQL = "UPDATE Table SET field=0.11 WHERE id=12456"
db.Execute SQL, dbSeeChanges

在提交时使用params:

<% if @events != nil %>
    <%= form_tag events_swap_path(@carpool) do %>
        <div><%= submit_tag 'Swap!' %></div>
        <% @events.each do |event| %>
        <tr>
            <td><%= event.driver.name%></td>
            <td><%= event.name%></td>
            <td><%= event.drop_off? ? "Drop Off At" : "Pick Up From" %></td>
            <td><%= event.location_name%></td>
            <td><%= event.is_game ? "Game" : "Not Game(event, practice)" %></td>
            <td><%= event.location_address %></td>
            <td><%= event.date ? event.date.strftime("%A, %d %b %Y %l:%M %p") : "Please Enter Details on TeamSnap!"%></td>
            <td>
                    <%= check_box_tag 'event_ids[]', event.id %>
            </td>
        </tr>
        <% end %>
    <% end %>
<% end %>