Rails 4.2 Tutorial 1 - Setup

  • Feb 6

Rails 4.2 is the last big release of 4.x series before Rails 5. This is a tutorial on how to write a bookmarking application in Rails.

To set up a proper environment, you can use rvm. After that, install Rails by gems:

gem install rails

To create an application, do this:

rails new bookmark --skip-bundle --database=postgresql

This uses Postgresql as database, which in my own opinions is better than MySQL. And it does not run bundle yet because we need to add some more gems.

To set up PostgreSQL for rails, you can follow this article. The main point besides installing PostgreSQL is add an user for Rails like this:

create role bookmark with createdb login password 'password1'

Then you have to match the username and password to Rails config/database.yml.

You will also note that for production database in config/database.yml, the password is in an environment variable (ENV['BOOKMARK_DATABASE_PASSWORD']). It is now a common practice to put sensitive information in environmnet variable and do not check into the git repository.

Another secret you should keep is in config/secrets.yml. Again, it is in an environment variable for production. Rails does not mendate how these environment variables are managed. Here will use Figaro for that.

First, we need to add it into the Gemfile:

gem 'figaro'

Then install it

$ bundle install

And follow Figaro's instruction:

$ figaro install

Then you can put secret and postgresql user password in production into config/application.yml like this:

SECRET_KEY_BASE = 'xxx' # you can get the with `rake secret`

In figaro, you can also separate the environment variables by development, test and production mode.

Then set up the database by:

$ rake db:migrate

Since the secret is safely guarded, set up git repository.

$ git init
$ git add .
$ git commit -m 'init'

Now, everything is ready to go. Fire up the rail sserver:

$ rails server

And link to http://localhost:3000. Now a working rails application is running.

A few extra gems might help in the long way: