Search code examples
ruby-on-railslink-to

How to delete multiple records using check_box_tag and link_to - Rails4


In my routes I have

delete 'boshu_hombu/delete_data', :as => :delete_data

In my controller, the delete method

def delete_data
  if params[:boshus]
    BoshuHombu.where(id: params[:boshus]).destroy_all
  end  
  redirect_to edit_all_path
end

In my views I am selecting multiple records for delete using checkbox, I have a button to invoke delete action

<%= link_to '削除',  { action: :delete_data}, method: :delete,
 data: { confirm: 'Are you sure?' }, :class => 'btn btn-danger' %>
<% @get_boshu_data.each do |user| %>
  <tr>
    <td><%= check_box_tag "boshus[]", user.id %></td>
    <td><%= user.id %></td>
    <td><%= user.kyujin_site %></td>
  <tr/>
<% end %>

but how to get the selected values in my controller's delete_data action. How to go about this ? thank you


Solution

  • try this:

    <%= link_to '削除',  { action: :delete_data}, method: :delete,
     data: { confirm: 'Are you sure?' }, :class => 'btn btn-danger', id:'delete' %>
    <% @get_boshu_data.each do |user| %>
      <tr>
        <td><%= check_box_tag "boshus[]", user.id, false, class: 'check' %></td>
        <td><%= user.id %></td>
        <td><%= user.kyujin_site %></td>
      <tr/>
    <% end %>
    
    <script>
    $(document).ready(function(){
     var href = $('#delete').attr('href')
    
     $('#delete').on('click',function(){
       var newHref = href + '?'
       $('.check').each(function(){
        if ($(this).prop('checked') == true) newHref+='boshus%5B%5D='+$(this).val()+'&'
       });
       $('#delete').attr('href',newHref)
    
     });
    
    });
    </script>