Now, we could take the easy way out and generate a rails scaffold instead of a resource, which will set up everything for us, including the routes, controller actions, views, style, etc. However, we want to really learn how to build this task manager step-by-step, so we will take the long and hard route. I promise that it's worth the effort, and you will learn a lot in the process.
What's a resource? A resource is any object that you want users to be able to access via URI and perform CRUD (create, read, update, delete) operations on.
We need a Task resource for our to-do list, which has description
and completed
attributes. So let’s generate the Task
model using the rails generate resource
command. This command creates an empty model, controller, and migration to create the tasks
table.
➜ bin/rails generate resource task description:string{200} completed:boolean
Running this command will create a 20220212031029_create_tasks.rb
migration file under the db/migrate
directory. The exact name will be different as Rails uses the timestamp to generate the name of the migration file.
This file should have the following content.
class CreateTasks < ActiveRecord::Migration[7.0]
def change
create_table :tasks do |t|
t.string :description, limit: 200
t.boolean :completed
t.timestamps
end
end
end
Let’s run the migration to create the tasks
table. This will run the SQL command to create the table in the database.
➜ bin/rails db:migrate
== 20220212031029 CreateTasks: migrating ======================================
-- create_table(:tasks)
-> 0.0021s
== 20220212031029 CreateTasks: migrated (0.0022s) =============================
If you open your SQLite database using a database browser, you should see a tasks
table in the database.