DEV Community

Robert Chen
Robert Chen

Posted on • Originally published at Medium on

Launch a Rails database in under 5 minutes

A step by step tutorial

This will be strictly instructional, follow this step by step guide to quickly build your backend.

1) In your terminal: rails new APP-NAME --api

  • Or add this flag if you have Postgres installed and would like to use it: rails new APP-NAME --database=postgresql —-api
  • If you choose to use Postgres, remember to turn Postgres on when you launch your server.

2) In your terminal: cd APP-NAME && open Gemfile, then find and uncomment gem 'rack-cors', then add this line of code on the next line: gem 'active_model_serializers'

3) In your terminal: bundle && open config/initializers/cors.rb, then uncomment the following code and use * for origins:

4) In your terminal: open config/routes.rb, then add namespacing and resources:

# resources :posts, only: [:index, :create] is an example for when you have more models.

5) In your terminal: rails g model User username password_digest

  • Replace User with the model that you need.
  • Replace username with the attributes that you need.
  • We’re going to keep User as our example model going forward.

6) In your terminal: open app/models/user.rb, then add your relationships:

7) In your terminal: rails g controller api/v1/Users

  • Replace Users with the controller that you need.

8) In your terminal: open app/controllers/api/v1/users_controller.rb, then add methods:

9) In your terminal: rails g serializer User

  • Replace User with the model that you need.

10) In your terminal: open app/serializers/user_serializer.rb, then add attributes and relationships to other models:

  • Uncomment has_many :posts after creating your other model(s).

11) In your terminal: rails db:create && rails db:migrate

12) Test this by running rails c in your terminal then User.create(username: 'bob')

  • Ctrl + D to quit.

13) Launch! Type rails s in your terminal then go to [http://localhost:3000/api/v1/users](http://localhost:3000/api/v1/users) in your browser.

  • Ctrl + C to quit.
  • If not localhost:3000, your terminal will tell you:
// rails s
=> Booting Puma
=> Rails 5.2.2 application starting in development
=> Run `rails server -h` for more startup options
Puma starting in single mode…
* Version 3.12.0 (ruby 2.3.4-p301), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Enter fullscreen mode Exit fullscreen mode

Repeat steps 4–10 for your other models and that’s it, you’re done (with your backend).


Bring your friends and come learn JavaScript in a fun never before seen way! waddlegame.com

Top comments (0)