Welcome to the next step in building our ToDo App using Ruby on Rails! In this lesson, we will recall the GET
queries and set up methods to fetch all ToDo
items and specific ToDo
items by their ID
. These operations are crucial for displaying the list of ToDos
and viewing details about each item.
By the end of this lesson, you will learn how to:
- Fetch all
ToDo
items from a service and display them in a list. - Retrieve a specific
ToDo
item by itsID
and show detailed information about it.
Here's a quick look at the essential code you'll be working with:
app/controllers/todos_controller.rb
Ruby1class TodosController < ApplicationController 2 def index 3 @todos = TodoService.get_all 4 end 5 6 def show 7 @todo = TodoService.get_by_id(params[:id]) 8 end 9end
In app/services/todo_service.rb
, we have:
Ruby1class TodoService 2 @@todos = [ 3 { id: 1, title: 'Sample Todo 1', description: 'Description 1' }, 4 { id: 2, title: 'Sample Todo 2', description: 'Description 2' } 5 ] 6 7 def self.get_all 8 @@todos 9 end 10 11 def self.get_by_id(id) 12 @@todos.find { |todo| todo[:id] == id.to_i } 13 end 14end
The above code snippets show how we define controller actions to interact with our ToDo
service.
Understanding how to set up GET
queries is fundamental for any web application. These queries enable your app to read and display data effectively.
Imagine a ToDo
list app that can list all tasks but can't display details of a specific task. That wouldn't be very useful, right? By learning to implement these GET
queries, you will build the backbone of your ToDo
app, making it functional and user-friendly.
Excited to see your app in action? Let's move on to the practice section and start coding together!