Thursday, May 3, 2007

Set Up Ruby on Rails with Postgresql

To set up Ruby on Rails to work with Postgresql, do the following:
Install Ruby:
sudo aptitude install ruby rdoc irb libyaml-ruby libzlib-ruby ri libopenssl-ruby


Install RubyGems (this is an aptitude/apt-get style utility that handles ruby programs)
Get the latest version from here
wget http://rubyforge.org/frs/download.php/17190/rubygems-0.9.2.tgz
tar xzvf rubygems-0.9.2.tgz
cd rubygems-0.9.2/
sudo ruby setup.rb
sudo gem update --system


Install Rails using RubyGems:
sudo gem install rails -y


Install PostgreSQL:
sudo aptitude install postgresql-8.2 postgresql-client-8.2 postgresql-client-common postgresql-common postgresql-doc-8.2


Now you have two choices. You can either install a pure Ruby PostgreSQL driver for Rails called postgresql-pr (slower) or you can install the native driver postgresql.

To install the postgresql-pr driver
sudo gem install postgres-pr


To install the postgresql driver
You need to install some more packages, or the installation will fail:
sudo aptitude install ruby1.8-dev libpq-dev
POSTGRES_INCLUDE=/usr/include/postgresql sudo gem install postgres


Enabling PostgreSQL
To start using PostgreSQL under your username, you first have to create a new PostgreSQL user. After a fresh installation of Postgres, the only (Linux) user that can create databases/users is the user "postgres", so we must "login" under its name.
sudo su postgres

Now we use the createuser script to create a new user.
createuser -P

(-P means "assign password") You will be asked some questions, just answer as follows, replacing YOUR_USER_NAME with your user name (BEEP cyclic redundancy check error BEEEEP)
Enter name of role to add: YOUR_USER_NAME
Enter password for new role:
Enter it again:
Shall the new role be a superuser? (y/n) y
CREATE ROLE

Now type
exit

to become yourself again.

Your First Rails Project
When you create your Rails projects, you have to tell Rails to use your PostgreSQL database, like this:
rails my_super_duper_project -d postgresql

Now, with your new super duper project created, you must modify the config/database.yml file so that Rails knows your username and password. In that file you will find THREE (3) "paragraphs" that look like this:
  adapter: postgresql
database: YOUR_PROJECT_DATABASE
username: YOUR_USER_NAME
password:

Just change the password fields to match your password. Also, you can notice that there are three databases, one that ends with "_development", another one with "_test" and another one with "_production". You create these databases using the createdb script:
createdb YOUR_PROJECT_development
createdb YOUR_PROJECT_production
createdb YOUR_PROJECT_test


Links of Interest
Ubuntu wiki's Rails Page
PostgreSQL in Ruby on Rails
RubyGems download page
Glom's initial Posgres configuration page

1 comment:

supie said...

hey bro, thanks for the guide.. its worked for me..