Aipack
Aipack

Reputation: 94

Update multiple records in table selected with checkboxes - Rails

i have a table that list all the article records, each row have a checkbox. Users can select multiple articles and choose spesific action to the selected record using checkboxes . Similar like table for user with admin roles. User can select action from dropdown menu something like this

With Selected : - Delete Articles
                - Publish Articles
                - Unpublish Articles

My question is how to connect these menu to the correspond method in the controller?

resources :articles do
    collection do
      delete 'delete_multiple'
      patch 'publish_multiple'
      patch 'unpublish_multiple'
    end
  end

controller

def delete_multiple   
    Article.destroy(params[:article_ids])
end

def publish_multiple  
    Article.where(id: params[:article_ids]).update_all(published: true)
end

right now i only can connect one of these menu (delete_multiple) by using form_tag to submit the selected ids

    <%= form_tag delete_multiple_articles_path, method: :delete, id: 'form-listing' do %>
    <table >
         <th>Tittle</th>
         <th>Content</th>
         <th></th>
         <td><%= article.tittle %></td>
         <td><%= article.content %></td>
         <td><%= check_box_tag "article_ids[]", article.id ,false %></th>
   </table >
  <%= end %>

and using link_to to execute form submit

 <ul class="dropdown-menu">
   <li><%= link_to 'Delete Selected', '#', :onclick => '$('#form-listing').submit();', %></li>
   <li>Publish Articles </li>   #? what to put here?
   <li>Unpublish Articles</li>  #? what to put here?
 </ul>

any advice guys?

Upvotes: 0

Views: 1120

Answers (1)

chumakoff
chumakoff

Reputation: 7044

It is usually done like this: you have a single action for all operations with multiple records. When you choose the operation the form is submitted with a corresponding value.

# routes.rb

resources :articles do
  collection do
    patch 'batch_operation'
  end
end

# controller

def batch_operation   
  case params[:operation]
  when "delete"
    Article.destroy(params[:article_ids])
  when "publish"
    Article.where(id: params[:article_ids]).update_all(published: true)
  # ...
  end
end

Upvotes: 1

Related Questions