A bigger project from my portfolio is a CMS written in Ruby on Rails, which I've called Blog on Rails for now. But I need a few smaller (and sooner finished) projects. The first one is a simple backend for a todo list application. I'm writing it also in Ruby on Rails, but I'm only writing the backend API part.
Creating a rails application and generating basic files
Ruby on Rails is a great fullstack framework, but for now I'm building only the API. First step is to create a Rails app:
Shellrails new todo_rails_backend --api -d sqlite3
I'm using --api for generating only backend parts. Since I want to use SQLite for the database, I use the command -d sqlite3.
Moving to app directory:
Shellcd todo_rails_backend
Next I have to generate a Task model:
Shellrails generate model Task title:string description:text due_date:date completed:boolean
This will generate a model, test for the model, and migration. Now I need to generate a controller for Task:
Shellrails generate controller Tasks
Implementation of Tasks controller
Create Action
Now let's implement a task controller. At the beginning we have an empty database and we need to create records. So let's start with the create action.
Rubyclass TasksController < ApplicationController
def create
@task = Task.new(task_params)
if @task.save
render json: @task, status: :created, location: @task
else
render json: @task.errors, status: :unprocessable_entity
end
end
private
def task_params
params.require(:task).permit(:title, :description, :due_date, :completed)
end
end
We create a new instance of the Task model using the parameters received from the request. Parameters are defined in the private method task_params.
If the task is successfully saved, the backend renders the JSON representation of the created task along with the HTTP status 201 Created. It also includes the Location header pointing to the newly created task's URL.
Last few steps before creation of the first task. We need to add resources to routes.rb:
routes.rbRails.application.routes.draw do
resources :tasks
end
Run database migration:
Shellrails db:migrate