Programming Note on Rails Backend and React Frontend With Example

Chengzhou (James) Jiang
The Startup
Published in
4 min readJun 30, 2020

One thing I realized as a programmer is that, we try to avoid repetition in our code, but we repetitively go to the same website to check the exact same syntax many many times. Let’s take a quiz:

Say you are building a restaurant app backend with rails. What is the correct syntax to claim a restaurant has many customers through orders.

A: has_many :Orders

has_many :Customer through :Orders

B: has_many: orders

has_many: customers, through: orders

C: has_many :orders

has_many :customers, through :orders

Which one do you think is the correct answer?

3

2

1

If you say C, congratulations! You are, the closest! Yes, none is correct. The correct answer is:

D:

has_many :ordershas_many :customers, through: :orders

If you are super detail oriented and figured out none of the top 3 were correct, well, you still need this note because you will forget.

The goal of this note is that, if you are a full stack developer who uses rails and react very often, you will not need to go to the same 10 websites a thousand times to check for the same syntax, you only need to visit this blog 1000 times.

Let’s build that restaurant app from scratch. Before you start, you should already figured out the models and their relationships. Let’s keep it simple. You have 2 parents models, Restaurant, Customer; and 1 join model, Order.

Back End First.

  1. You need to create a folder. In your terminal, go to your coding project directory/folder, and type:
mkdir “Restaurant App”cd Restaurant Appmkdir “BackEnd”mkdir “FrontEnd”cd BackEnd

2. Now you are in the back end directory, let’s go ahead and start the rails magic:

rails new restaurant-api --api

3. Then, navigate into the new Rails application once created. Run bundle install, and let’s create models:

rails g resource restaurant name genrerails g resource customer name age:integerrails g resource order restaurant:references customer:references

4. This will create three migrations, three models, and three empty controllers. Check the migration file, and if everything looks cool, run:

rails db:migrate

5. Check the models, the ActiveRecord created some relationship for you, but you may need to put some on your own.

class Restaurant< ApplicationRecord
has_many :orders`
has_many :customers, through: :orders
end
class Customer < ApplicationRecord
has_many :orders
has_many :restaurants, through: :orders
end
class Order < ApplicationRecord
belongs_to :restaurant
belongs_to :customer
end

6. Look at the your config/routes.rb . In there you can see everything written in resources. If you want to customize with only the routes you want to include:

resources :orders, only: [:index, :show]

7. Go to your controllers

class RestaurantsController < ApplicationController
def index
restaurants = Restaurant.all
render json: restaurants, include: [:order, :customer]
end
def show
restaurant = Restaurant.find(params[:id])
render json: restaurant
end
def create
restaurant = Restaurant.create(restaurant_params)
render json: restaurant
end
private
def restaurant_params
params.require(:restaurant).permit(:name, :address)
end

8. Setting up CORS. In the Gemfile, uncomment

# gem ‘rack-cors’

and run bundle install. Then, add the following to config/application.rb inside class Application < Rails::Application

config.middleware.insert_before 0, Rack::Cors do
allow do
origins ‘*’
resource ‘*’,
:headers => :any,
:methods => [:get, :post, :delete, :put, :patch, :options, :head],
:max_age => 0
end
end

This shouldn’t replacing anything.

And that’s it for a basic Rails BackEnd to function! Take a break and we will continue with the React Front End.

For the React Front End, things are a little easier.

  1. You first need to navigate to the FrontEnd folder. If you never used react on this computer before, you may want to run this to make sure you computer has it installed
npm install -g create-react-app

2. Then

create-react-app restaurantnpm start

3. This should give you the basic environment set up. You may then want to write a function component:

function App() {return (<div></div>);}

Or a class component:

class App extends React.Component{state = {   restaurantList: []}componentDidMount() {   fetch("http://localhost:3000/restaurants")   .then(response => response.json())   .then((restaurantObjs) => {   this.setState({      restaurantList: restaurantObjs})})}
render(){ return ( <> <Header/> </> ); }}

4. When you write a fetch post request and need to write headers

handleSubmit = (e) => {   e.preventDefault()   fetch("http://localhost:3000/restaurants", {method: "POST",headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: this.state.restaurantName, image: this.state.restaurantAddress,})}).then((response) => response.json())}

This is it! I hope this note saves your time, and happy coding!

--

--