This is the first of two-part article series about building a mobile app using Ionic and Rails.
We will build a Todo App, to make it simple. First, we are going to build the backend and create the API. Then, in the second article, we will build the UI with Ionic and React to consume the API created.
In this two-part article series, we will guide you through building a Todo app using the Ionic Framework and Rails. In this first article, we will show you how to create the backend and API using Rails. With instructions and code snippets, you'll be able to f create your API in no time.
Then, in the second article, the UI with Ionic and React will be built to consume the API created. Ionic is an open-source UI toolkit for building mobile apps using web technologies, while Rails is a web application development framework written in the Ruby programming language.
The article provides instructions on enabling CORS, creating models, controllers, and routes, as well as performing CRUD operations and making HTTP requests to test the endpoints using an HTTP client. The source code is available on GitHub.
Rails
Rails is a web application development framework written in the Ruby programming language. It is designed to make assumptions about what every developer needs to make web applications easier.
Requirements
Ruby installed
Rails installed
NodeJs installed
Android Studio installed
Creating the REST API
We choose a directory where we want to develop our application and write the following command to create a new Rails API:
rails new todo_api --api
Enable CORS
We want that our Ionic mobile app consumes the REST API, so we have to enable CORS first.
We go to config/initializer/config.rb
. We will a file like this:
# Be sure to restart your server when you modify this file.
# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests.
# Read more: https://github.com/cyu/rack-cors
# Rails.application.config.middleware.insert_before 0, Rack::Cors do
# allow do
# origins "example.com"
#
# resource "*",
# headers: :any,
# methods: [:get, :post, :put, :patch, :delete, :options, :head]
# end
# end
We need to un-comment from line 8 to line 16:
# Be sure to restart your server when you modify this file.
# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests.
# Read more: https://github.com/cyu/rack-cors
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins "*"
resource "*",
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
We replace origins "example.com"
with origins "*"
.
Then, we go to Gemfile and un-comment the line where gem "rack cors"
is. And run bundle install
command on the terminal.
Creating the model, database, controllers, and routes.
To create the database, models and controllers folder, we run the following command:
rails g resource todo_task
We go to db/migrate/<timestamp>create_todo_task.rb
to define the attributes of the todo_task
table. There will be two attributes: task
as a string, and completed
as a boolean.
task
will show what task we have to do, and completed
will show its status.
class CreateTodoTasks < ActiveRecord::Migration[7.0]
def change
create_table :todo_tasks do |t|
t.string :task
t.boolean :completed
t.timestamps
end
end
end
We run the following command in our terminal, to migrate the table:
rails db:migrate
CRUD operations
We go to app/controllers/todo_task_controller.rb
to create the functions that will allow our app to perform CRUD operations.
Index
def index
@todo_tasks = TodoTask.all
render json: @todo_tasks
end
This controller dispatches a list of all tasks in the database.
Show
def show
@todo_task = TodoTask.find(params[:id])
render json: @todo_task
end
The show
controller sends the task requested by its ID.
Create
def create
@todo_task = TodoTask.create(
task: params[:task],
completed: params[:completed]
)
render json: @todo_task
end
This controller inserts a new task into the database. And sends the new task added as JSON to the client.
Update
def update
@todo_task = TodoTask.find(params[:id])
@todo_task = TodoTask.update(
task: params[:task],
completed: params[:completed]
)
render json: @todo_task
end
The update
controller extracts the ID parameter and looks for a record in the database that matches. Then, proceeds to update the record.
Destroy
def destroy
@todo_tasks = TodoTask.all
@todo_task = TodoTask.find(params[:id])
@todo_task.destroy
render json: @todo_tasks
end
The destroy
controller deletes the record according to the ID parameter in the request.
Routes
The Rails router recognizes URLs and dispatches them to a controller's action.
Rails.application.routes.draw do
resources :todo_tasks, only: [:index, :show, :create, :update, :destroy]
end
We set up the resources the router will serve when receiving an HTTP request from a client.
Seed Data
In db/seed.rb
we created two records to display when we make HTTP requests.
task_1 = TodoTask.create(task: "Buy fruits", completed: false)
task_2 = TodoTask.create(task: "Buy cheese", completed: true)
Then we run the following command to apply the changes.
rails db:seed
HTTP Requests
Now, we make HTTP requests to make sure our API behaves as we expect.
We start the server by running the following command:
rails s
Using an HTTP client, we try all the endpoints.
GET requests
Index
Show
POST request
PUT request
DELETE request
Conclusion
In conclusion, this article focuses on creating the backend and API using Rails, with detailed instructions and code snippets to help you follow along and create your API. The article covers enabling CORS, creating models, controllers, and routes, as well as performing CRUD operations and making HTTP requests. The source code is available on Github, and the article also provides references to additional resources for further learning.
Thank you for taking the time to read this article.
If you have any recommendations about other packages, architectures, how to improve my code, my English, or anything; please leave a comment or contact me through Twitter, or LinkedIn.
The source code is here.
References
Ionic Framework documentation.
Beginner's guide to creating an API from scratch using Rails.
Top comments (0)