How To Build A Web App, part 7 of ?: connecting our Rails app to our database

Mikey Clarke
8 min readSep 16, 2019
The end is in sight. Today we’ll write a tiny bit of actual code.

This is the seventh in a series of articles taking you through all the actual steps in building a web app. If you’re an aspiring developer, if mucking around with teensy beginner tutorials frustrates you, if you’d love to build a properly substantial app that does fab things, these articles are for you.

Last time we installed PostgreSQL. Now we’ll connect it to our app.

And now, actual code! It’s the seventh bloody article and only now are we actually jumping in to the Gigs app itself!

I’ve been trying to space out different techs and concepts as much as I can, because holy crap web dev has a lot of them, but if you’ll forgive me dumping yet another one on you, before we kick off with actual Rails programming, let’s talk about code editors.

Editing code bases isn’t like editing a Word doc. It’s just one file. I’ve attacked code bases with thousands of files. Up to a point you can get away with having a Finder window side-by-side with a standard text editor, but things become chaos fast. Besides, a good code editor has zillions upon zillions of other programmer-friendly features, which we’ll skim across in later articles.

Code editor culture is its own nifty self-contained maelstrom of one-up-womanship and vicious rivalries. I don’t intend to get into that here, more’s the pity, but! I’m quite fond of Sublime Text. It’s plenty good, use that. Install it and open your Gigs app folder in it.

Great, done? Now comes time for actual programming.

In Sublime Text’s left-side file-explorer-thing, you’ll see a file there called Gemfile. Open it. It should look something like this.

I saw the great big UNREGISTERED in the upper right corner, I thought “ooh that ain’t a good look, I’d better get around to registering my copy” … and I genuinely can’t figure out how. Clicking on it doesn’t do anything. There aren’t any options in the menus that I can find. Zip.

The Gemfile is a special file inside your Rails project. Most Ruby-based projects have one. You may recall Rubygems and Gems and Gemfiles from Article 3, back when you installed Rails on your own machine. A project’s Gemfile controls what third-party gems you want installed for your particular project, and the program Bundler manages this. To hook our app to our PostgreSQL server, we’ll need to modify two files: Gemfile, and another file, config/database.yml.

We’ll use Gemfile to tell Rubygems to install a gem called pg, which does the actual connection work between Rails and PostgreSQL. We load our own app-specific config into it with database.yml.

This right here is a new feature! You know how in articles 4 and 5 I promised I’d take you through both Git’s general workings, and a Git feature branch? Here’s our first example. Let’s do it.

Hop back on your command line. Run this:

$ git checkout -b 1-connect-database

checkout -b does two things: it creates a new Git branch, then does something called “checking it out”.

What’s that? Remember when we first discussed Git, we used the analogy of editing a Word doc, wanting to retain all the changes each time you save it, and saving a new copy, a new file, on every save event. That’s the essence of what Git’s all about. Each commit is another copy of your code-base state.

But! All these Git copies are behind-the-scenes stuff. You only have a single actual physical folder/file structure visible to you. If you open Finder, you’re not going to see multiple copies of your app stretching to infinity each time you commit. Git hides these.

How do you access them, then? That’s checkout’s job. The command creates a new Git branch, branching off the central branch (master), and then checks it out. The files and folders inside your Gigs folder are your new branch’s content.

And finally, 1-connect-database is simply that branch’s name. 1 is an ID number (just to keep track of the branches, because later on there’ll be a ton of ’em), and connect-database is a rough-and-ready label. I brushed on naming conventions back when discussing Git commit messages (another thorny universe), but I find something like [ID]-[label] works well enough.

You can see your newly created branch via git branch without any arguments or flags at all. The command just simply lists all your branches:

$ git branch
* 1-connect-database
master

Sweet! Your new branch exists, and the asterisk states which branch you’ve checked out. Moving on.

Now! The feature’s actual code changes. Let’s get our database hooked up.

Recall we modify two files: Gemfile and config/database.yml.

Gemfile is easy: to hook up the Rails app to the PostgreSQL database, just change where it says gem 'sqlite3' to gem 'pg'. You don’t have to, but you can also delete the comment above gem 'sqlite3' , where it says # use sqlite3 as the database for Active Record, as that comment is now out of date. You discover bloody quick in your coding career that the only thing worse than no comment is a wrong comment.

If reading my written description of these changes merely bamboozles you, then if you like, you can totally see my own commit, and its Gemfile changes, recorded on Github.

One thing you’ll need to do after every Gemfile modification is to run this:

$ bundle install

This is a command to the program Bundler. You’re telling it to go over your Gemfile and actually go through the installation process for any gem not already installed. Exactly what that means is beyond the scope of this article, but if you like, go nuts with this article. That’ll explain things.

The second file, config/database.yml,is a bit different. Quick context: I’m sure you can guess that anything inside the config folder pertains to your app’s configuration. database.yml is a text file containing the data your app needs to connect to your database. It’s pairs of keys and values.

Here’s what you do. On line 8, change adapter: sqlite3 to adapter: postgresql.On line 14, change database: db/development.sqlite3to database: gigs_development, and below that, add the lines username: [your OS's login name], and below that, password: , yes, an empty string. The development: section in my own file, for example, now looks like this:

development:
<<: *default
database: gigs_development
username: michaelclarke
password:

My machine’s username is michaelclarke, and when you install PostgreSQL with defaults-only, it picks yours as its default username.

If you’re still unclear, here is the exact before/after I have in mind, from my own commit.

And those are all the changes you’ll need. You’ve now given your app everything it needs to connect to PostgreSQL.

Now fire up Git and commit these changes. git status will take you through them:

$ git status
On branch 1-connect-database:
Changes not stages for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: Gemfile
modified: Gemfile.lock
modified: config/database.yml
no changes added to commit (use "git add" and/or "git commit -a")

Wait a sec. What’s Gemfile.lock?

I’d better explain. Bundler manages two files. Gemfile is a file you edit yourself. You manually type out which gems you’d like to use.

Gemfile.lock is a whole ‘nother beastie. It’s automatically generated by Bundler. Its job is dependency management. See, each gem may depend on other gems to work, and those gems might depends on gems of their own, and these gems each have their different versions, and the versions might clash, and on and on and on.

It can get rather hairy. I’ll go through an example. You know how Rails itself is a gem? Here’s the Gemfile.lock dependency entries for Rails:

rails (5.2.3)
actioncable (= 5.2.3)
actionmailer (= 5.2.3)
actionpack (= 5.2.3)
actionview (= 5.2.3)
activejob (= 5.2.3)
activemodel (= 5.2.3)
activerecord (= 5.2.3)
activestorage (= 5.2.3)
activesupport (= 5.2.3)
bundler (>= 1.3.0)
railties (= 5.2.3)
sprockets-rails (>= 2.0.0)

actioncable, eh? All right, what’s its dependencies?

actioncable (5.2.3)
actionpack (= 5.2.3)
nio4r (~> 2.0)
websocket-driver (>= 0.6.1)

And actionpack's?

actionpack (5.2.3)
actionview (= 5.2.3)
activesupport (= 5.2.3)
rack (~> 2.0)
rack-test (>= 0.6.3)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.0.2)

And actionview

actionview (5.2.3)
activesupport (= 5.2.3)
builder (~> 3.1)
erubi (~> 1.4)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.0.3)

And activesupport

activesupport (5.2.3)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 0.7, < 2)
minitest (~> 5.1)
tzinfo (~> 1.1)

concurrent-ruby is the first one on that list that doesn’t have its own dependencies. It’s seven layers deep! Seven! In the dark days before fabulous dependency managers like Bundler, ancient bastards like moi had to install each and every one of these ourselves. Manually. Kids these days, eh? Don’t know how lucky you’ve got it! Get off my lawn!

Gemfile.lock is Bundler’s internal scratchpad to keep track of the exact version of every single gem your app needs. The file gets updated whenever you run bundle install.

But in any case. We’re done hooking up our database! Test this by firing up your web server. It’s time to actually run your Gigs app.

Back on your command line, run rails server. This fires up a web server that comes bundled with Rails. Your command line should show something like this:

$ rails server
=> Booting Puma
=> Rails 5.2.3 application starting in development
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.12.1 (ruby 2.5.0-p0), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:3000
Use Ctrl-C to stop

Awesome. Now, open your web browser, and go to this URL: http://localhost:3000

If all has gone well, you should see this:

That’s the default Rails server screen, a blank placeholder. We’ll swap it out with our fabulous maps app later.

Now, finally, we make our Git commit.

Just like back in Article 4, execute git add ., then git commit -m "Added our database config". Again, you don’t have to use this exact message text. If you like, you can use whatever text tickles your fancy.

Here is the entire code base at this commit.

The feature is complete. Now we merge the branch back into master.

$ git branch
* 1-connect-database
master
$ git checkout master
Switched to branch 'master'
Your branch is up to date with 'origin/master'
$ git merge 1-connect-database
Updating 20d9f0a..163cd85
Fast-forward
Gemfile | 4 ++--
Gemfile.lock | 4 ++--
config/database.yml | 6 ++++--
3 files changes, 8 insertions(+), 6 deletions(-

And done. Next time: database schema design.

PS Those of you intermediate-and-above may be shitting bricks right now at me not having added database.yml to .gitignore. I know, I know. I’ll get there eventually. If you don’t know what I’m on about, though, you can safely disregard this paragraph.

--

--

Mikey Clarke

Hi there! My snippets and postings here are either zeroth drafts from my larger novels, or web-app tutorials and other computery codey musings.