Back-end Engineering Articles

I write and talk about backend stuff like Ruby, Ruby On Rails, Databases, Testing, Architecture / Infrastructure / System Design, Cloud, DevOps, Backgroud Jobs, and more...

Twitter:
@daniel_moralesp

2020-03-13

Rails & React Apps

#1- Todo List App

Resources

To install in a current project

# Gemfile
gem 'webpacker'

# console
$ rails webpacker:install

# inside /config/webpack add staging environment file if its neccesary. Just copy de 
# same as production but change for staging names

Things that I feel, I'm doing different with this tutorial

- rails API under /api/v1/route
- This API is protected by Devise
- This API don't have inheritance from ::API base controller, but with ::Base
- The authentication is not manage via Devise Auth Tokens, or any tokens at all, 
is managed by normal cookies as devise works
- The test of the API can't be manage trough Postman, because we don't have any
tokens. It need to be dealt under csfr-token that all Rails apps has, just 
like the tutorial does, but I have to allow Cross Origin
- the react features are manage trought webpacker gem
- the react front-end will be under /javascript folder
- the react code need to call Turbolinks



#2- Beer App


Link Tutorial: https://www.honeybadger.io/blog/react-rails/

Commands

$ rails new crud-rails-react
$ rails g scaffold Beer brand:string style:string country:string quantity:integer
$ rails db:migrate

## Add to Gemfile
gem 'webpacker'

## console
$ bundle install
$ bundle exec rake webpacker:install
$ bundle exec rake webpacker:install:react

**## EVERYTHING NOW NEEDS TO BE DONE VIA YARN NOT NPM**

## add react and others
yarn add react
yarn add antd react-router-dom

Keys on the building blocks of react Rails app that is built as Monolith

  1. Install webpacker and React with them
  2. Add everything in react via Yarn, not NPM
  3. Create Rails scaffold, but separaing controller to API Controller
  4. Respond just via JSON under that controller
  5. Explicity create Routes, not as resources, because Rails made inferences
  6. Initial setup of React in the rigth folders
  7. From React make API calls to the specific routes
  8. Add protect_from_forgery with: :null_session in application's controller

#3- Todo App


Link: https://www.youtube.com/watch?v=k1HjmeqF0p0

Im creating this underthe project, where api is nder rails and react woith NPM is creating react-app

Commands

# danielmorales is a full-stack rails app, so I don't have API Base, 
# instead the normal Base controller

$ rails g scaffold todo task:text

## then
- delete todo stylesheets
- delete todo js
- delete todo helpers
- delete todo views
- create api/v1 controller folder
- create route namespace

## constroller
class Api::V1::TodosController < ApplicationController

## routes
namespace :api do
  namespace :v1 do
    resources :todos
  end
end

New controller responding with JSON

class Api::V1::TodosController < ApplicationController
  before_action :set_todo, only: %i[show update destroy]

  # GET /todos
  def index
    @todos = Todo.all

    render json: @todos
  end

  # GET /todos/1
  def show
    render json: @todo
  end

  # POST /todos
  def create
    @todo = Todo.new(todo_params)

    if @todo.save
      render json: @todo, status: :created, location: @todo
    else
      render json: @todo.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /todos/1
  def update
    if @todo.update(todo_params)
      render json: @todo
    else
      render json: @todo.errors, status: :unprocessable_entity
    end
  end

  # DELETE /todos/1
  def destroy
    @todo.destroy
  end

  private

      # Use callbacks to share common setup or constraints between actions.
      def set_todo
        @todo = Todo.find(params[:id])
      end
  
      # Only allow a trusted parameter "white list" through.
      def todo_params
        params.require(:todo).permit(:task)
      end
end

Create new record and test in route

$ rails s -p 3001


Screen Shot 2022-05-29 at 2.04.00 PM.png 126.58 KB

Creating the front end

  • In a new terminal window, create reac-app (it takes a while)
$ npx create-react-app todo-frontend
$ npm start

Create normally all the React app components, and use NPM, because now er're in React itself, not in a monolith from Rails unique app (in that case we use Yarn)

This app works, pay attention to the Create method, and I have to finished with Update method:

Kind of implementations
* React via yarn and webpacker, tutorial one (bad tutorial) but it was fixed here (https://github.com/danielmoralesp/crud-rails-react-v3), and two (bad tutorial)
* React via gem, tutorial
* All views with React
* Views mixed between React and erb, (good tutorial, it doesn't have the Routes management in React, repo here: https://github.com/danielmoralesp/rails-react-todo-application)
* Rails API Only and React front
* A possible good tutorial. Not bough yet.

Creating Launchbook, I'm here: https://stevepolito.design/blog/rails-react-tutorial/#step-3-create-todo-item-model