CRUD with Rails and React (p1)

Tram Ho

Introduce

When learning a new language or framework, I personally find the best approach is to make an app fully functional CRUD. So in this article, let’s write a Rails application that uses React as the front end with CRUD functions.

Initialize the Rails application

Start with this familiar command to create a rails application:

Then add gem 'react-rails' gem gem 'react-rails' to Gemfile folder and run bundle install Next run rails g react:install command. This statement will

  • Add some Reactjs libraries //= requires to the application.js file
  • Add the components/ directory for React components. You can see more details here. Next let’s add a model called Fruit . This app will only work with this one model

In the file db/seed.rb add the following content:

Then run the command rails db:migrate db:seed to initialize the database and create the data. That’s all, prepare the environment and data.

Controller

First, in the file app/controllers/application_controller.rb we add the following line:

to better understand the function protect_from_forgery you can see more articles of this

Our application is API based so the controller directory structure should follow the following namespace convention: app/controllers/api/v1 . Versioning for the API means changes can be made in the future without damaging the specific original version here v1 . We will create a file in the app/controllers/api/v1 called fruits_controller.rb . In this file we will write code to create the basic CRUD methods.


def create
fruit = Fruit.create fruit_params
render json: fruit
end

def destroy
Fruit.destroy params
Share the news now

Source : Viblo