This episode combines the technique shown in Episode 017 habtm checkboxes and Episode 35 Custom REST Actions to update a task’s complete attribute through checkboxes.]
Some of the differences in this episode were the methods used to update the complete
attribute. In episode 035, the update_attribute()
was used to update a single record. In this episode we used the update_all()
method. There was a slight difference in how the update_all()
method was used in the video and how it is currently used. In the video the update_all()
method accepts two arguments, the attribute with updated value, plus the ids of tasks to be updated. The update_all()
method has been changed to accept only one argument, the attribute with the updated value. This creates some problems in specifying which record to update. Luckily, the API for update_all showed the correct way to use the updated version of update_all()
.
Task.where(id: params[:task_ids]).update_all([“complete=?”, true])
We use the where()
method to return tasks fitting the passed in conditional.
The params[:task_ids]
were sent from the form within the view.
<%= form_tag complete_tasks_path, method: :put do %>
<ul>
<% @incomplete_tasks.each do |task| %>
<li>
<%= check_box_tag "task_ids[]", task.id %>
<%= task.name %>
</li>
<% end %>
</ul>
<%= submit_tag "Complete task" %>
<% end %>
Here we use the form_tag
because the form is not directly editing attributes on a model. We then specify the path and method to put
. I am just realizing this now, but this put
should be a patch
to match up with what the Rails core team has been doing in transitioning from put
to patch
to match with RFC’s specifications.
The next part to focus on is the <%= check_box_tag "task_ids[]", task.id %>
line. We are creating checkboxes for each task with the value of the task’s id. The name for each checkbox can be specified to task_ids[]
because we are using a general check_box_tag
. task_ids[]
allows the task_ids
parameter sent from the form to be an array able to hold multiple records. This is where we get the params[:task_ids]
array passed into the where()
method.