Creating a React Native App With a Ruby On Rails Backend (Part 1 of 3)

Written by Armaiz Adenwala

In this two-part tutorial we will build a simple note taking app, using a Ruby on Rails api and a React Native client. Completing it will allow you to practice the basic skills needed to develop real-world applications with React Native and Ruby on Rails.


Note: I will be using ruby 2.4.2 and Rails 5.0.7.2 for this project. You can check your Ruby versions by running ruby -v and rails -v.


Set up the Ruby on Rails API


To start, create a rails app by running rails new noteApi --api in your terminal. Once the command finishes, we can run cd noteApi to move into the api codebase.


Sqlite3 has a bug that can stop the server from running on a fresh Rails app. Thankfully, the fix is straightforward.


In Gemfile we need to replace gem 'sqlite3' with gem 'sqlite3', '~> 1.3.0'.

    
source 'https://rubygems.org'
​
...
  
gem 'rails', '~> 5.0.6'
gem 'sqlite3', '~> 1.3.0'
gem 'puma', '~> 3.0'
​
...
    
  

To install the new sqlite version, we need to run bundle install.


Now, run rails server -p 5000 in the terminal to run the Rails server on port 5000.


Create the Notes Model


The next step is to generate a Note model. The model will have one attribute called text which will contain the text content of the Note.


Run rails g model Note text:string to generate the model. This will tell Rails to create a model that has a string attribute called rails g model Note text:string. The command also creates a model in app/models/, a test under test/, and a database migration in db/migrate. ​


Implement the Database Migration


The generated database migration from the command above looks like this:

    
class CreateNotes < ActiveRecord::Migration[5.0]
  def change
    create_table :notes do |t|
      t.string :text
​
      t.timestamps
    end
  end
end
    
  

​This migration will generate a table called notes in our database via create_table:notes, with attributes text and timestamps. Timestamps are autogenerated by Rails and reference the created_at and updated_at attributes.


​To implement the migrations, run rails db:migrate. This will update our sqlite database with our new notes table.


​Create the Notes Controller


​We need to generate a controller to handle API requests by running rails g controller Notes. This command will create a controller under app/controllers/.

    
class NotesController < ApplicationController
    
  

As you can see, we will need to add some actions to the file so the controller can handle the API requests.


Add Resource Notes to routes.rb


We can check if rails has routes pointing to this controller by running rails routes.

    
$ rails routes
You don't have any routes defined!
​
Please add some routes in config/routes.rb.
​
For more information about routes, see the Rails guide: http://guides.rubyonrails.org/routing.html.
    
  

There are no routes defined, so we need to add routes to our routes.rb file. Rails uses resource routing, which automatically creates routes for a controller. We can implement this by adding resources :notes to our routes.rb file.

    
Rails.application.routes.draw do
  resources :notes
end
    
  

Now, run rails routes

    
$ rails routes
Prefix Verb   URI Pattern          Controller#Action
notes GET    /notes(.:format)     notes#index
      POST   /notes(.:format)     notes#create
note  GET    /notes/:id(.:format) notes#show
      PATCH  /notes/:id(.:format) notes#update
      PUT    /notes/:id(.:format) notes#update
      DELETE /notes/:id(.:format) notes#destroy
    
  

Rails automatically created 6 routes. For this guide, however, we are only worried about creating a note and displaying all notes. These two actions map to two routes:

    
 notes GET    /notes(.:format)     notes#index
       POST   /notes(.:format)     notes#create
    
  

The GET call will automatically direct to notes#index and look for an action called index in the new controller we just created. Similarly, the POST call will automatically direct to notes#index and look for an action called create.


To restrict the resources :notes to only use the two routes mentioned above we need to add only: [:index, :create] to the end of the line. Our resulting config/routes.rb file will look like:

    
Rails.application.routes.draw do
  resources :notes, only: [:index, :create]
end
    
  

After running rails routes again, we can see the GET and POST endpoints were the only routes created.

    
$ rails routes
Prefix Verb URI Pattern      Controller#Action
 notes GET  /notes(.:format) notes#index
       POST /notes(.:format) notes#create

    
  

Implement Index and Create Endpoints


Add a def index action in the notes_controller.rb file.


    
class NotesController < ApplicationController
  def index
    notes = Note.all
    render json: notes, status: :ok
  end
end
    
  

The action pulls all notes from the database using notes = Note.all and returns it as json using render json: notes, status: :ok. We haven’t created any notes yet, so it will return an empty array: [].


In order to add a note, update the NotesController with `def create` and `def note_params` .

    
class NotesController < ApplicationController
  def index
    notes = Note.all
    render json: notes, status: :ok
  end

  def create
    note = Note.create!(note_params)
    render json: note, status: :ok
  end
​
  def note_params
    params.require(:note).permit(:text)
  end
end
    
  

The line params.require(:note).permit(:text) in note_params is performing many tasks. The params is the JSON object we pass in our POST api call. The .require(:note) call looks for a note object in the params, and will throw an error if it is missing. The .permit(:text) call finds the text parameter in the note object and returns a new object.


The line above will now accept the following JSON, for example:

    
{
  "note": {
    "text": "Hello",
    "pointlessKey": 'World'
  }
}
    
  

It will return:

    
{
  "text": "Hello",
}
    
  

Looking back at the create action, we can see it creates a new note in the database using the note_params method defined above. If it succeeds, it will continue on the next line and render the JSON of the new object.

    
def create
  note = Note.create!(note_params)
  render json: note, status: :ok
end
    
  

Using the APIs


We can test our endpoints using curl. Make sure the Rails server is running on port 5000 in one terminal tab and test the GET endpoint by running curl localhost:5000/notes/ in another tab.


Now that we’ve built the api, let’s test it out.

    
$ curl localhost:5000/notes/
[]%
    
  

The array we get back is empty, because we haven’t created any notes yet. To create a new note, we will first create a simple JSON note, then pass it into our curl request.


    
{
  "note": {
    "text": "Hello"
  }
}
    
  

Use the -H flag to set the Content-Type header as JSON and use the -d flag followed by the JSON above to pass in the note.

    
$ curl localhost:5000/notes -X POST -H 'Content-Type: application/json' -d '{"note": {"text": "Hello"}}'
{"id":28,"text":"Hello","created_at":"2019-09-24T16:42:07.389Z","updated_at":"2019-09-24T16:42:07.389Z"}%
    
  

If successful, the api will return the note object with additional console output. If the request fails, check that your api is running and that your curl syntax is correct.


Finally, make a GET request to view the new note.

    
$ curl localhost:5000/notes/
[{"id":28,"text":"Hello","created_at":"2019-09-24T16:42:07.389Z","updated_at":"2019-09-24T16:42:07.389Z"}]%
    
  

Success!

The Rails server is now complete. In the next post of this series, we will set up the React Native app, and connect it to our Rails servers.


---
At FullStack Labs, we pride ourselves on our ability to push the capabilities of cutting-edge frameworks like React. Interested in learning more about speeding up development time on your next project? Contact us.

Let’s Talk!

We’d love to learn more about your project. Contact us below for a free consultation with our CEO.
Projects start at $25,000.

FullStack Labs
This field is required
This field is required
Type of project
Reason for contact:
How did you hear about us? This field is required