Building a mobile app with Ionic Framework and Rails
Published: 2023-06-20 17:43:22

---
title: Building a mobile app with Ionic Framework and Rails
published: true
date: 2023-03-13 16:03:18 UTC
tags: 
canonical_url: https://carlosmv.hashnode.dev/building-a-mobile-app-with-ionic-framework-and-rails
---

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](https://github.com/carlosm27/todo_api_rails).

### 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

```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678210408793/2d493c6a-c6bc-4a70-8eb5-9f5b666f262f.png)

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

```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678212109042/f13ef097-4d44-46c9-be74-221de546e359.png)

### 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

```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678292735462/05c1cdfe-919b-4147-a5db-910df9e279e7.png)

Using an HTTP client, we try all the endpoints.

#### GET requests

Index

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678292855245/2717dd23-1e74-48a3-b9ba-09ae3dc574c8.png)

Show

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678292902987/d576199f-9699-4c81-9e1e-f335170ac223.png)

#### POST request

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678293045018/53e82cd7-04b3-4775-b9c6-5c3a75ab2e16.png)

#### PUT request

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678293912013/22bf1f38-89ac-40f8-b4ce-cde250f63167.png)

#### DELETE request

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678294036585/be0732d6-ce12-446e-a2ad-0d98f07dbb0e.png)

### 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**](https://twitter.com/Carlos_marcv), or [**LinkedIn**](https://www.linkedin.com/in/carlos-marcano-a2135a134/).

The source code is [here](https://github.com/carlosm27/todo_api_rails).

### References

[Ionic Framework documentation.](https://ionicframework.com/docs)

[Rails Guides.](https://guides.rubyonrails.org/)

[Beginner's guide to creating an API from scratch using Rails.](https://dev.to/lisahjung/beginner-s-guide-to-creating-an-api-from-scratch-using-rails-2eie)