Multiple update with checkbox in Rails
Updating multiple items through checkbox is implemented usually in many applications. Let see how to select some or all items using checkbox and update the selected items in Ruby on Rails 1. Configuring the routes: For building the applications in the REST way, we can create ...
Updating multiple items through checkbox is implemented usually in many applications.
Let see how to select some or all items using checkbox and update the selected items in Ruby on Rails
1. Configuring the routes:
For building the applications in the REST way, we can create tasks_controller in both the namespace "multiple" and the "standard" routes
config/routes.rb
namespace :multiple do resource :tasks, only: :update
2. Generating the controllers:
We can use update_all to update several attributes for multiple records. Note that update_all don't update the timestamp
app/controllers/multiple/tasks_controller.rb
class Multiple::WorkFlowsController < ApplicationController def update Task.where(id: params[:task_ids]).update_all completed_at: Time.now redirect_to :back end end
3. Get the checkboxes form for selecting multiple items:
By using the check_box_tag, all the values'll be passed into an array
app/views/tasks/index.html.erb
<% form_tag multiple_tasks_path, :method => :get do %> <table> <% for task in @incomplete_tasks %> <tr> <td> <%= check_box_tag "task_ids[]", task.id %> <%= task.name %> </td> </tr> <% end %> </table> <%= submit_tag "Mark as Complete" %>
**4. Check all checkboxes: **
In this article, we use javascript to select all the items when clicking on the checkall checkboxes
app/views/tasks/index.html.erb
<%= check_box_tag "check_all", "check_all", false, class: "check_all" %> <% form_tag multiple_tasks_path, :method => :get do %> <table> <% for task in @incomplete_tasks %> <tr> <td> <%= check_box_tag "task_ids[]", task.id, class: "task-updatable" %> <%= task.name %> </td> </tr> <% end %> </table> <%= submit_tag "Mark as Complete" %> <script type="text/javascript"> $(document).on("click", ".check_all", function(e) { $(".task-updatable").prop("checked", !this.checked); $(".task-updatable").click(); }); </script>
Conclusion
For updating multiple record with checkboxes, here a good way to separate the controllers and the views but not the model and still kept the application in the REST way.