Deploy Rails and PostgreSQL to Heroku - SEIR-59/course-wiki GitHub Wiki

Deploying Rails & PostgreSQL to Heroku

By Sam Whindleton - WDIR-Outrun
How to deploy an existing repo to an existing Heroku app & Heroku database setup.

Follow below steps if you have:

  1. A Rails and PostgreSQL app.

  2. The repo on GitHub.

  3. An app on Heroku.

Connect Repo to Heroku

Heroku Dashboard

  • In a browser go to your Heroku Dashboard

    • Login if required.
  • Select your app.

    heroku-dashboard

  • Select the Resources tab.

    • If you see Heroku Postgres :: Database go to step Select the Deploy tab.

    resources

    • Else: Type postgres in the Add-ons field and select Heroku Postgres

    add-postgres

  • Select the Deploy tab.

    deploy

  • Scroll to the bottom of the page, you'll need the name of your heroku app repo.
    This might be different than the name of your github repo.

    heroku-app-repo

Terminal

  • Connect local repo to existing Heroku app. DO NOT TYPE $

    $ heroku git:remote -a foobar
    
  • Push to Heroku

    $ git push heroku master
    

Heroku Database(PostgreSQL) Setup

Terminal

  • Connect to your Heroku App database

    $ heroku pg:psql
    
    • You'll see something similar to:

    heroku-db

  • Create tables, populate data, etc.
    Example:

    -- create a table
    CREATE TABLE foobar (id SERIAL, foo VARCHAR(24), bar TEXT);
    
    -- add data
    INSERT INTO foobar (foo, bar) VALUES
    ('tomato', 'is it a fruit or vegetable?'),
    ('pear', 'so many pears to chose from.'),
    ('apple', 'honeycrisp apples are my favorite.');

Rails Files

  • Open a rails model file from the app/models directory

    $ app/models/foobar.rb
    

    directory

  • Edit the database connection
    You'll need to do this for every model.

    class Foobar
      attr_reader :id, :foo, :bar
    
      # if heroku, use heroku psql db
      # --------------------------------------------------
      # if statement shouldn't require change
      if (ENV['DATABASE_URL'])
        uri = URI.parse(ENV['DATABASE_URL'])
        DB = PG.connect(uri.hostname, uri.port, nil, nil, uri.path[1..-1], uri.user, uri.password)
      # --------------------------------------------------
    
      # else, use local psql db
      else
        DB = PG.connect(
          host: "localhost",
          port: 5432,
          dbname: 'foobar')
      end
    
      def initialize(opts = {})
        @id = opts["id"].to_i
        @foo = opts["foo"]
        @bar = opts["bar"]
      end
    
      # CODE HERE
      # ...
      # ...
    
    end

  • git push to github and heroku.

  • You can now user your local database while developing, and heroku will use its database on production.

Done.

⚠️ **GitHub.com Fallback** ⚠️