How to add a checkbox for each row in Rails 3.2 in

2019-06-09 04:07发布

问题:

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

There are a couple of questions we don't quite understand:

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.

回答1:

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
}


回答2:

for identifying each checkbox you should use <%= check_box_tag "object_ids[]", object.id %>, it will return to your controller and array with all the ids of the objects that you check on submit, check this video of Ryan Bates that is where i learn this technique, regards



回答3:

If all you need is a way to get info / effect the row a checkbox was clicked on, then this may help.

JS:

$('yourTableHere').on('click', 'input', function(){
    $(this).parentsUntil('tr').toggleClass('active'); // any functionality can go here
});

Demo Fiddle