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:
1 2 | rails new fruits-app |
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 amodel
calledFruit
. This app will only work with this onemodel
1 2 | rails g model Fruit name:string description:text |
In the file db/seed.rb
add the following content:
1 2 3 | fruits = ['Mango', 'Pineapple', 'Passion fruit', 'Dragonfruit'] fruits.each{|fruit| Fruit.create(name: fruit, description: "I am a delicious #{fruit}.")} |
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:
1 2 3 4 | class ApplicationController < ActionController::Base protect_from_forgery with: :null_session end |
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.
1 2 3 4 | class Api::V1::FruitsController < ApplicationController def index render json: Fruit.all end |
def create
fruit = Fruit.create fruit_params
render json: fruit
end
1 |
def destroy
Fruit.destroy params
1 2 |