Setting up your Full Stack Application: Rails API and React/Redux
By: Waverley Leung
Tags: Guides And Tutorials, React, Code Newbie, Rails, Redux

Setting up your Rails API

To reiterate, the following steps are what I often do when I set up my Rails API. That being said, there may be some steps (i.e. gems) that you will not want/need for your project. Also, I often create my Rails API with Postgres as the database. Whatever database you choose to work with isn’t as important as some of the other steps, but I will emphasize what each part is doing so that you can be conscious of your own project.

Go to the project directory that is holding your Rails API Change into the Rails API folder with:

cd <rails_api_folder_name>

3. In your Gemfile uncomment:

gem ‘bcrypt’

gem ‘rack-cors’

Bcrypt is what we will be using to hash our users’ passwords. The rack-cors gem provides support for Cross-Origin Resource Sharing (CORS), which is when a web application is making a cross-origin HTTP request that has a different origin (i.e. domain) than its own.

4. In your Gemfile you can choose to add any or all of the following gems:

gem ‘jwt’

gem ‘active_model_serializers’

gem ‘activerecord-reset-pk-sequence’

The ‘jwt’ gem is for setting up JSON Web Token for user authentication. The gem for serializers allows us to use serializers, which give us control over what is being sent out to the frontend. The last gem (activerecord-reset-pk-sequence) is for your seed data and will reset the id of your Active Record table to zero.

5. 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. If you’re interested in learning more about CORS, check out this in-depth explanation by Chris.

6. In your terminal run:

bundle install

spring stop

Only if you included gem ‘activerecord-reset-pk-sequence’ in your Gemfile do you need to run spring stop.

7. If you want to include multiple serializers and have it show more than one association deep (in other words, if you are serializing deeply nested associations), create a new file in config/initializers. Inside the new file, add the following line of code:

ActiveModelSerializers.config.default_includes = '**'

You can name the file anything, but I suggest naming it “active_model_serializers.rb”. Also, even though this allows you to use your serializers with nested associations, the associations can only go in one direction.

8. Create your models, migrations, controllers, and routes files with:

rails g resource <model_name> <attribute:datatype>

rails g resource Book title:string pages:integer author:belongs_to

Don’t forget to add your associations! You can use the belongs_to macro to set up your foreign keys and belongs_to association. However, that means you need to create based on the has_many first; simply put, create models that are independent/don’t rely on others for information first. Think about it: you can’t create a book without an author first.

Fun fact: Normally you would also get your views folder, but if you generated the app with the --api flag, it configures the generators to skip the views folder.

Bonus: If you are using Bcrypt for your user’s password, instead of password being the attribute (password:string), you would be using “password_digest” as the column in the table. However, it is only in your schema and migration that you will be using “password_digest”. Everywhere else, including when you create a user instance, you will be using “password”. For example:

rails g resource User name:string age:integer password_digest:string

User.create!(name: “bob”, age: 15, password: “pw321”)

9. Go into each model’s file (app/models) to add validations and/or the rest of your association macros for the models that need it. If we continue with the author and book example, you could add to the author model:

has_many :books

validates :first_name, presence: true

If you are using Bcrypt for the user’s password, you can use a macro in your user model called has_secure_password.

10. If you are using serializers, for each serializer be specific about the association macros you use. The association macros here have nothing to do with your model association macros and you should think about which association is more important to send out to your frontend.

11. Create your Postgres database with:

rails db:create

12. Run your migrations and create your schema with:

rails db:migrate

13. Specify the routes you will need in routes.rb. You will get all of the RESTful routes automatically because of rails g resource, (based on the earlier example it would look like resources :books) but if you know you won’t need all of them you can individually write out what you need.

14. Create some seed data in your db/seeds.rb and seed it with:

rails db:seed

Before creating seed data you might want to test in your console (rails c) if you can create instances of each model. To be more specific, you should check if your validations and associations are working. In addition, at the top of this file, for each class you can include class_name.destroy_all and class_name.reset_pk_sequence starting from the classes that are dependent/belongs_to.