Initializing Rails API App

Installing Rails

gem install rails -v '~> 5.1'

Setting up a Rails API app

rails new repo-backend -T --skip-spring -C -M -d postgresql --api
  • -T amounts to skipping the built-in testing framework. We’ll test our API with something other than MiniTest, so let’s drop it for now.
  • --skip-spring removes Spring from our application; that’s a personal preference. If you don’t know what Spring does and whether you should remove it, I urge you to find out and decide for yourself.
  • -C skips Action Cable. No web socket communication for us!
  • -M skips Action Mailer, which wouldn’t be of any use to us.
  • -d postgresql of course, sets us up for the PostgreSQL database.
  • --api - now we’re talking! This runs the Rails generator in the API mode, which sets us up for reading and writing JSON instead of pumping out HTML.
  • An app/jobs directory was generated for us. We know that there will be no jobs in this application for the foreseeable future, so we can drop that.
  • There are four initializers that are commented out by default: backtrace_silencers.rb, application_controller_renderer.rb, inflections.rb and mime_types.rb. We may as well remove those.
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins ENV.fetch('ALLOWED_ORIGINS') { '*' }
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete,:options,:head]
end
end

Setting up the database

default: &default
adapter: postgresql
encoding: unicode
host: <%= ENV.fetch["db_host"] %>
user: <%= ENV.fetch["db_user"] %>
password: <%= ENV.fetch["db_password"] %>
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
timeout: 5000
test:
<<: *default
database: rails_backend_test
development:
<<: *default
database: rails_backend_development
production:
<<: *default
database: <%= ENV['DATABASE_URL'] %>
bundle install
bundle exec rails db:create
bundle exec rails db:migrate
bundle exec rails s
bundle exec rails db:migrate RAILS_ENV=production\
bundle exec rails server -e production -p 3002

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store