Learn react on railsSort Order

Rails API: Setting up Basic CRUD - [002]

In this episode we show you how to setup the basic CRUD for our front-end app. We begin by generating the model, then the routes and controller to enable the endpoints to be accessed by our react app.

Let's begin by creating the model using

rails g model contact

This will generate us the model in app/models/contact.rb and a migration file in our db/migrate/TIMESTAMP_create_contacts.rb . Let's hop into our migration file.

class CreateContacts < ActiveRecord::Migration[5.0]  def change    create_table :contacts do      t.string :first_name      t.string :last_name      t.string :email            t.timestamps    end  endend

Let's run our migration

rails db:migrate


We'll need to generate the controller for our endpoint.

rails g controller v1/contacts

This will have generated the controller for us in app/controllers/v1/contacts_controller.rb . Let's fill out our controller

class V1::ContactsController < ApplicationController  def index    @contacts = Contact.all        render json: @contacts, status: :ok  endend


Let's setup the route so we can actually send requests to our controller in config/routes.rb

Rails.application.routes.draw do  namespace :v1 do    resources :contacts  endend

To see what the router has generated we can use

rails routes

This will print out the routes for us. We can access this routes by starting our server using rails s in the console and pointing the browser to localhost:3000/v1/contacts

Create Action

Let's continue and fill out our other actions inside of the app/controllers/v1/contacts_controller.rb

# ...def create  @contact = Contact.new(contact_params)    @contact.save  render json: @contact, status: :createdendprivatedef contact_params  params.require(:contact).permit(:first_name, :last_name, :email)end# ...

Destroy Action

Let's also add the destroy action.

# ...def destroy  @contact = Contact.where(id: params[:id]).first    if @contact.destroy    head(:ok)  else    head(:unprocessable_entity)  endend# ...

That'll wrap up this episode in the next episode (the front end part we'll implement the UI that consumes these endpoints).