Day 5: Task Views – Adding the ability to complete a task

Task Views

Yes, there are many task views. One for each controller action. This is what edit view looks like.

Views are simply HTML templates with some ruby code mixed in them. Ruby code is located inside <%= %> tags. Like this: <%= ruby_code_goes_here %>

HTML and Ruby code in a view

Views can render other views called partials. In our case, edit view renders form partial. Partials are located in the same directory as views. The only difference is that partial’s filename starts with the underscore symbol.

Lets look at form partial a little closer.

Rails form partial

3 Things:

  1. form_for method takes @task instance variable as a parameter. It generates an HTML form. This form is meant for editing the @task.
  2. Name field contains the name of the @task.
  3. Submit button submits the form and it’s fields to a server.

Adding the ability to complete a task

We can change the name of a task. Let’s add the ability to complete the task. We’ll add a checkbox. If the checkbox is checked, then completed field changes to true. If it’s unchecked, it is set back to false.

We need to make 2 changes in order to make it happen:

  1. Let’s use check_box method inside our form to add a checkbox.

Add a checkbox to a form2. We need to come back to app/controllers/tasks_controller.rb. TasksController needs to trust completed attribute.

Whitelist completed attribute

That’s it! Go back to you browser, navigate to the previously created task at http://localhost:3000/tasks/1/edit

Completed checkbox

Look! It’s our completed checkbox. Right now it’s unchecked. Check it and click Update Task button. The task is saved.

Let’s check if it was really saved into our database. Click edit link to return back to edit screen. If you see completed checkbox checked, then it was indeed saved. Congratulations, my friend.

What happened here?

We looked at a rails view. The view is a mix of HTML and Ruby code. We added completed checkbox to edit view. After that we whitelisted completed attribute inside TasksController so we can save it.

We can successfully complete our tasks. Although, task completeness is not displayed on any other views. Let’s change that next.

Photo by Alan Cleaver