For my Phase 5 project requirement with Flatiron School, I built a personal portfolio website. Read on to quickly set up your project with Rails API and React/Redux frontend.
First is to create your project directory that will hold both your API and frontend folders. I decided to build two separate repositories for these because it is easier to merge repositories later on than it is to split them.
mkdir <your_project_folder_name>
Create your Rails API folder. I connected my React app with a PostgreSQL database right away as I’m planning to deploy the app right after.
rails new <rails_api_folder_name> --api --database postgresql
Change into your Rails API folder.
cd <rails_api_folder_name>
Add the gems you need or want for your app. In your Gemfile, uncomment:
gem ‘bcrypt’
gem ‘rack-cors’
bcrypt is a secure hash algorithm for safely storing passwords.
Rack::Cors provides support for Cross-Origin Resource Sharing (CORS) for Rack compatible web applications. Uncomment the following code in config/initializers/cors.rb and change “example.com” after origins to ‘*’:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
Changing the origins to ‘*’ allows any origin to make a request. Check out this in-depth explanation to learn more about CORS.
In your terminal run:
bundle install
It’s time to work on your models, migrations, controllers, and routes files. Create your Postgres database and run your migrations.
rails g scaffold user username email password_digestrails db:createrails db:migrate
It is important to check and make sure your models, validations and associations are all working in your rails console.
rails cexit
Once everything is set and working, you may seed data in your db/seeds.rb and run:
rails db:seed
Don’t forget to push your code to GitHub!
Let’s start building your React application.
Go to your main project directory. Use the create-react-app
generator to start your React app. For a detailed instruction, check out this repo to setup.
npx create-react-app <react_app_folder_name>
Change into your React app folder.
cd <react_app_folder_name>
In your terminal type the following to install packages.
npm i redux react-redux react-router redux-thunk --savenpm start
Don’t forget to push your code to GitHub!