Lesson 1
Setting Up GET Queries - Get All and Get By ID
Setting Up GET Queries - Get All and Get By ID

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.

What You'll Learn

By the end of this lesson, you will learn how to:

  1. Fetch all ToDo items from a service and display them in a list.
  2. Retrieve a specific ToDo item by its ID 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

Ruby
1class 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:

Ruby
1class 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.

Why It Matters

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!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.