This is one of those episodes I needed to see. I haven’t had to use the collection or member blocks in the routes file before, but I’m glad to know what they mean now. member
and collection
allows the developer to create custom RESTful routes that extends the rails conventions. A member
route appends after the /:model/:id
, so the controller action has the params[:id]
. A collection
route appends after the /:model
route.
Examples of these two were the routes created in this episode.
resources :tasks do
get 'completed', on: :collection
put 'complete', on: :member
end
This creates the normal RESTful Rails routes, but it also create two custom routes. /tasks/completed/
and /tasks/:id/complete
. The Rails Guides for Routing was useful for further reading.
TasksController
def completed
@tasks = Task.where(completed: true)
end
def complete
@task.update_attribute :completed, true
flash[:notice] = 'Task Completed'
redirect_to completed_tasks_path
end
The two custom actions were completed
and complete
The completed
action returns a tasks instance variable where completed
is true. The complete
action updates an attribute to true, then redirects to the completed tasks view with a flash notice.
To complete a task, the episode shows creating a link with the put method being sent the complete_task_path
while sending the task’s id.
Heroku Issue
For some reason when I tried to click on this ‘complete task’ link, heroku is giving me a ‘page doesn’t exist’ error. Locally the link works however. I have opened a StackOverflow question about the issue. I don’t think you need a view for that action because it redirects to the completed_tasks_path. Even the rake routes show a PUT for /tasks/:id/complete
. I did discover that the Rails core team has been switching over to the Patch
verb over the put
http verb. This adheres to RFC specification for partial updates. Even though I tried to change out put
for patch
, I was unable to get this link working.