Bootstrap with Rails and Postgres

in rails •  2 months ago

> rails new app_name you all you need to get started developing an application, notably using SQLite as the default datastore. I've always worked with Postgresql (postgres) since I started with rails development, so the first thing I end up doing when scaffolding an application is bootstrap it with postgres. If you are newer to postgres and/or rails then this post is intended as a brief guide on how to do just that.

Postgres is a professional-grade, open-source, object-relational database system. While you could use SQLite for development, and postgres for production, there are some inconsistencies between the two. There is no real benefit to doing this if you are working on an application you ever plan to expose to the outside world.

It is fairly simple to get postgres setup once you have it installed on your machine. So, here's a quick breakdown of how I like to configure things with a new app to get up and running quickly. If you need help installing postgres on your machine check this out.

The generator

First things first, we need to take another look at our generator line above. Let's set postgres as our database:

> rails new app_name -d postgresql

This simply sets up some configuration files, and adds the gem 'pg' to our Gemfile. Before we run the application, we’ll need to set up our database. Let's create a user using a cli installed with postgres:

> createuser --createdb --login -P whatever

You will be prompted for a password twice. --createdb tells postgres that
our user should be able to create databases. The --login switch will allow
our user to log in to the database and -P means we want to set our new user’s
password right now.

The config

Now, we need to add our username and password to our defaults in config/database.yml (see this guide for further instruction).

default: &default
  adapter: postgresql
  encoding: unicode
  host: localhost
  <mark>username: whatever</mark>
  <mark>password: your_password</mark>
  pool: 5

Almost done! Set up the database, run a migration, and start the rails server.

> rake db:create
> rake db:migrate
> rails server

We don’t have any database tables, but rails should complain if the database
config is off, so this is a decent test of what we've done. Jump over to localhost:3000
in your browser and you should see a running application. Painless.

Please note, you will not be able to deploy your application to production like this, and you should not check your config/database.yml into version control. For production, you'll want to use environment variables. I'd recommend the figaro gem for a simple solution.

(ノ◕ヮ◕)ノ*:・゚ * Until next time!

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  Trending

I like your writing style, easy to understand.