Ruby on Rails Switch From Sqlite3 to Postgres

Here is a very short tutorial on this. I needed to reference this from another post so its a bit quick and dirty. We are going to switch from using the sqlite3 in our local environment to using postgres.

Here is what we need to do:

  1. Install postgres on our local machine. Get Postgres
  2. Add a helpful tool called pgAdmin. Get pgAdmin
  3. Change our Gemfile in our rails app.
  4. Run bundle install to get postgres gem.
  5. Change the database.yml file to use postgres.
  6. Make sure Postgres is up on our machine. (just start the app and it should automagically start up)
  7. Run rake db:setup followed by rake db:migrate
  8. Run rails server
  9. Go to localhost:3000 and see no exceptions!

 

For One and Two above I have provided a couple of links to get postgres and a phpmyadmin type database tool so you can physically see data in the db. I’ll pick up here with number three.

3. Here we make a change to our Gemfile. We need to out sqlite3 and in postgres.

Before:

source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.8'

# Use sqlite3 as the database for Active Record
gem 'sqlite3'

# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.2'

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'

# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'

# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'

# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.2'

group :doc do
  # bundle exec rake doc:rails generates the API under doc/api.
  gem 'sdoc', require: false
end

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano', group: :development

# Use debugger
# gem 'debugger', group: [:development, :test]

After:

source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.8'

# Use postgres as the database for Active Record
gem 'pg'

# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.2'

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'

# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'

# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'

# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~>; 1.2'

group :doc do
  # bundle exec rake doc:rails generates the API under doc/api.
  gem 'sdoc', require: false
end

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~>; 3.1.7'

# Use unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano', group: :development

# Use debugger
# gem 'debugger', group: [:development, :test]

4. Now we need to run <b>bundle install</b> to get the newly added gem.

$ bundle install

5. Now we need to change our database.yml file located at <b>/config/database.yml</b>

Before:

# SQLite version 3.x
#   gem install sqlite3
#
#   Ensure the SQLite 3 gem is defined in your Gemfile
#   gem 'sqlite3'
development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: sqlite3
  database: db/production.sqlite3
  pool: 5
  timeout: 5000

After:

# PostgreSQL. Versions 8.2 and up are supported.
#
# Install the pg driver:
#   gem install pg
# On OS X with Homebrew:
#   gem install pg -- --with-pg-config=/usr/local/bin/pg_config
# On OS X with MacPorts:
#   gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config
# On Windows:
#   gem install pg
#       Choose the win32 build.
#       Install PostgreSQL and put its /bin directory on your path.
#
# Configure Using Gemfile
# gem 'pg'
#
development:
  adapter: postgresql
  encoding: unicode
  database: demo_test_development
  pool: 5
  username: dave
  password:
  timeout: 5000

  # Connect on a TCP socket. Omitted by default since the client uses a
  # domain socket that doesn't need configuration. Windows does not have
  # domain sockets, so uncomment these lines.
  #host: localhost

  # The TCP port the server listens on. Defaults to 5432.
  # If your server runs on a different port number, change accordingly.
  #port: 5432

  # Schema search path. The server defaults to $user,public
  #schema_search_path: myapp,sharedapp,public

  # Minimum log levels, in increasing order:
  #   debug5, debug4, debug3, debug2, debug1,
  #   log, notice, warning, error, fatal, and panic
  # Defaults to warning.
  #min_messages: notice

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: postgresql
  encoding: unicode
  database: demo_test_test
  pool: 5
  username: dave
  password:
  timeout: 5000

Here I’ve changed to the postgres adapter and added my username. In this case dave is my Mac username. The database: is my app name in this case demo_test followed by underscore development or test. There is no need to have a production setup here if you use Heroku like I do. Heroku will have its own db for your app and you wont have to config it like this.

6. Make sure postgres is up and running.If your on a Mac it should just start up by itself when you click the Application: postgres.app

7. Now we need to run <b>rake db:setup</b> and then <b>rake db:migrate</b> to get the database schema for our new db type.

$ rake db:setup
...
....some messages....
...
$ rake db:migrate

8. Start up the rails server by running <b>rails server</b>

$ rails server

9.Check our local URL. Most likely: http://localhost:3000 and we should be good to go! You should see the rails startup page that reads “welcome aboard” if you have an empty app.

*NOTE: If you ever want to create an app right from the get go that uses postgres try this command:

rails new my_app_name --database=postgresql

Basic Rails App with Bower

Ok, so the last two posts were about getting our skeleton set up so we’d have a Gemfile set up and ready to go for the next project.

This is a quick post on how to install Bower for your front end. I will make another post for another dependency manager called Rails-Assets.

It’s up to you which to use. Mainly the difference is this, Bower is the manual upgrade version. I say manual because we are going to manually decide each item we add and unless we manually change it, it will not change on us. (I would use this if I am going to use a js library that may not be future proof, or I want to include something from a private git repository that is a must have for my project.) It is also going to bundle any different versions of stuff it may need much like a gem.We’ll see this in a moment when we add Bootstrap, and we also get jQuery with it.

Rails-Assets is going to get you the newest versions of each component and automagically turn it into a gem for your application. It’s wonderful, but you may have a few bugs if there are any mismatches caused by updates.

So with out further discussion lets add Bower to our app skeleton.

First thing we are going to do is make sure we have NPM and Node installed. If you have home brew installed use:

brew install node

Get a cup of coffee, this might take a few minutes longer than you’d expect. Just wait it out. Here is a link to get instructions if you don’t use homebrew? Node Instructions (this should give you NPM too in one shot).

Next –

npm install bower

If that is all good, it’s time to open our Gemfile.

Here is the before:

source 'https://rubygems.org'


gem 'rails', '4.0.8'
gem 'pg'
gem 'sass-rails', '~> 4.0.2'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 1.2'

group :doc do
  # bundle exec rake doc:rails generates the API under doc/api.
  gem 'sdoc', require: false
end

#group :test, :development do
 #gem "rspec"
 #gem "rspec-rails", "~&gt; 2.0"
 #gem "factory_girl_rails", "~&gt; 4.0"
 #gem "capybara"
 #gem "database_cleaner"
 #gem "selenium-webdriver"
#end

Here is the After: (including a typo fix. “> to >”)

source 'https://rubygems.org'


gem 'rails', '4.0.8'
gem 'pg'
gem 'sass-rails', '~> 4.0.2'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 1.2'


#We do with Bower - INCLUDE BOWER FILE & ADD COMPONENTS TO ASSET PIPELINE
gem 'bower-rails'



group :doc do
  # bundle exec rake doc:rails generates the API under doc/api.
  gem 'sdoc', require: false
end

#group :test, :development do
 #gem "rspec"
 #gem "rspec-rails", "~> 2.0"
 #gem "factory_girl_rails", "~> 4.0"
 #gem "capybara"
 #gem "database_cleaner"
 #gem "selenium-webdriver"
#end

Now that we have added that gem, its time to use Bundle Install to get the job done. Should be green!

Now that we have finished this we need to create a Bower file and add in our components. To that we first need to create a blank file called Bower this file shouldn’t have an extension. Just put it in your app root like the Gemfile.

So, since I am a bootstrap fan let’s include that as our first component. It’s called “asset bootstrap-sass-official”. If you looked on the bootsrap there is always an official saas version and bower is going to get that for us. So our Bower file looks like this:

Before:


After:

asset 'bootstrap-sass-official'

Remember this goes in our root. Now it’t time to use a special command for Bower called

rake bower:install

This is going to generate some files and tell you about some other goodies we needed. In tis case you’ll see a reference to jquery. This little operation gave us some directories in /vendor/assets/bower_components.

Next we need to tell our app that we want these new goodies included in our config. To do this we add them to our /config/application.rb file. It’s not just a path so have a look closely.

Before:

require File.expand_path('../boot', __FILE__)

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module DemoTest
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = 'Central Time (US & Canada)'

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    # config.i18n.default_locale = :de
  end
end

After:

require File.expand_path('../boot', __FILE__)

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module DemoTest
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = 'Central Time (US & Canada)'

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    # config.i18n.default_locale = :de

    #For Bower
    config.assets.paths << Rails.root.join("vendor","assets","bower_components")
  end
end

Next we need to tell our app that we want these new goodies included in the asset pipeline. To do this we add them to the correct application file in our pipeline. For bootstrap we go to the /assets/stylesheets/application.css If this were a js component we’d go to /assets/javascripts/application.js. Here is our .css file:

Before

/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the top of the
 * compiled file, but it's generally better to create a new file per style scope.
 *
 *= require_self
 *= require_tree .
 */

After:

/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the top of the
 * compiled file, but it's generally better to create a new file per style scope.
 *
 *= require_self
 *= require bootstrap-sass-official/assets/stylesheets/bootstrap.scss
 *= require_tree .
 */

The path that we just added is the only way rails knows to load these specific Bower assets into the pipeline. In our case this is where the bootstrap.css file will come from. The path started from the bower_components/ directory.

*NOTE you will find on occasion that a file like bootstrap.scss might reference other files. Sometimes they need to also have the correct path referenced. Here is a place where glyphicons-halflings font needed to updated. You can see here where I had to change the path to the font to make it work since the bower component puts the font partial in its own folder at bootstrap-sass-official/assets/fonts/bootstrap/.

//= depend_on "bootstrap-sass-official/assets/fonts/bootstrap/glyphicons-halflings-regular.eot"
//= depend_on "bootstrap-sass-official/assets/fonts/bootstrap/glyphicons-halflings-regular.svg"
//= depend_on "bootstrap-sass-official/assets/fonts/bootstrap/glyphicons-halflings-regular.ttf"
//= depend_on "bootstrap-sass-official/assets/fonts/bootstrap/glyphicons-halflings-regular.woff"
//
// Glyphicons for Bootstrap
//
// Since icons are fonts, they can be placed anywhere text is placed and are
// thus automatically sized to match the surrounding child. To use, create an
// inline element with the appropriate classes, like so:
//
// <a href="#"><span class="glyphicon glyphicon-star"></span> Star</a>

// Import the fonts....

Anyway That’s it. We are ready to use Bower as our front end tool.

My Basic Ruby on Rails Set Up

If you read my last post you ended up with an empty rails skeleton and the standard Gemfile. I’ve made some changes to it. Here is a post on the changes.

Here is my new basic rails set up. I’ve been toying around with a lot of different set ups trying to dial in a set up for me that could help with rapid deployment for new apps. Really just a quick way to get up and running when I have an idea.

For me its always a lot easier if before running anything at the terminal, I get a short list together of what I want /need. Not too comprehensive, just a short list so I have a general idea of the goal and what I will need. Here is my short list so far. This is an empty Ruby on Rails setup. I’ll be adding few more things and posting a few more posts about it as the list gets more complete.

So far my new Gemfile looks like this:

source 'https://rubygems.org'

gem 'rails', '4.0.8'
gem 'pg' #### i'm a heroku guy so now its all I use for Ruby.####
gem 'sass-rails', '~&gt; 4.0.2'
gem 'uglifier', '&gt;= 1.3.0'
gem 'coffee-rails', '~&gt; 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~&gt; 1.2'

group :doc do
 # bundle exec rake doc:rails generates the API under doc/api.
 gem 'sdoc', require: false
end

#group :test, :development do
 #gem "rspec"
 #gem "rspec-rails", "~&gt; 2.0"
 #gem "factory_girl_rails", "~&gt; 4.0"
 #gem "capybara"
 #gem "database_cleaner"
 #gem "selenium-webdriver"
#end

I’ve commented out the gems I’d use of I was going to use rspec over mintest.

That’s about it for now. Next I’ll be getting the gems for Twitter Bootstrap and Devise so I can create a User and Admin user first thing. I like to think of the user as the person at the top of the tree that “has_many” of everything else.

Creating a New Rails App

Let’s assume you’ve already installed Ruby 4.0+ as well as Ruby Gems 2.0 +. You should also install Postrges on your local machine if possible. (Deploying with Heroku will be super easy and cheap if you use postgres on your local machine, so install it and come back.) Also here is my super quick and dirty tutorial on switching to postgres

If your not sure which Ruby version you have just go over to the terminal and enter:

ruby -v

That will give you your ruby version. For the gem version type

which gem

and you’ll be given a path if you’ve installed Ruby Version Manager (RVM) which i’d recommend. You’ll probably see something in the path like:

/Users/dave/.rvm/rubies/ruby-2.0.0-p481/bin/gem

Ok, so assuming that is all fine and well, lets use the terminal to get a New Rails App up so we can see what is output for us.

$ mkdir ruby_app
$ cd ruby_app
$ rails new my_new_app

And HOLLA –  a bunch of command line stuff like this:

create  
create  README.rdoc
create  Rakefile
create  config.ru
...

That created the basic skeleton of our new rails app. Let’s open up our new my_new_app directory inside our ruby_app directory that we created before we ran our command. Inside this new directory is a file called “Gemfile”. Let’s open this file up with an editor and have a look.

source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.8'

# Use sqlite3 as the database for Active Record
gem 'sqlite3'

# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.2'

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'

# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'

# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'

# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.2'

group :doc do
  # bundle exec rake doc:rails generates the API under doc/api.
  gem 'sdoc', require: false
end

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano', group: :development

# Use debugger
# gem 'debugger', group: [:development, :test]

Ruby created this entire file. We’ll use this file to add more gems like bootstrap and other great tools.

Let’s go over to the terminal now and run:

$ cd my_new_app
$ bundle install

Nothing special is supposed to happen here since we made no changes to the file. It’s going to output that long list again. This time each line will start with “Using gemname #.#.#”. We will use bundle install each time we make a change to the Gemfile. If we’ve added new gems, bundle install will go and load them in for us. The next post will have some simple changes to the Gemfile that I want to use so I can make a duplicatable and easy to deploy rails package that’s ready to go when I need it.