How to get PostgreSQL database to work with Rails app

April 25, 2012 Leave a comment

I am following the Rails by Tutorials book and in the middle of chapter 3, there’s an exercise to get PostgreSQL to work with Rails, I have spent quite an afternoon to do the research, so I thought I would document the long procedure here.
The book suggests that we check out the “Heroku instructions for local PostgreSQL installation”  The link does show how to install PostgreSQL on the local machine, but it does not show the rest, what we should do next to have working databases in the local machine.

I suppose that we have postgresql installed by using
$ brew install postgresql
as suggested in the Heroku documentation.
You can double check by running
$ psql --version
psql (PostgreSQL) 9.1.2
contains support for command-line editing

After the installation, what do we have? where’re the databases? how do we connect to them? The whole thing we want is “I just want to have a local working version of PostgreSQL to test my Rails app as with SqLite”

Or using the concept of the book, you just want all tests to be Green
$ bundle exec rspec spec/requests/static_pages_spec.rb

Finished in 0.47812 seconds
8 examples, 0 failures

Now, I’ll show you the next.
PostgreSQL is divided into 2 separate parts: client and server. The server needs to be started before any client applications can access the databases on the server. In order for the server to start, it needs to know where to store the databases, as suggested in the 2539-page PostgreSQL manual, we run this command:
$ initdb -D /usr/local/pgsql/data
The files belonging to this database system will be owned by user "pnhoang".
This user must also own the server process.

The database cluster will be initialized with locale en_US.UTF-8.
The default database encoding has accordingly been set to UTF8.
The default text search configuration will be set to “english”.

creating directory /usr/local/pgsql/data … ok
creating subdirectories … ok
selecting default max_connections … 20
selecting default shared_buffers … 1600kB
creating configuration files … ok
creating template1 database in /usr/local/pgsql/data/base/1 … ok
initializing pg_authid … ok
initializing dependencies … ok
creating system views … ok
loading system objects’ descriptions … ok
creating collations … ok
creating conversions … ok
creating dictionaries … ok
setting privileges on built-in objects … ok
creating information schema … ok
loading PL/pgSQL server-side language … ok
vacuuming database template1 … ok
copying template1 to template0 … ok
copying template1 to postgres … ok

WARNING: enabling “trust” authentication for local connections
You can change this by editing pg_hba.conf or using the -A option the
next time you run initdb.

Success. You can now start the database server using:

postgres -D /usr/local/pgsql/data
pg_ctl -D /usr/local/pgsql/data -l logfile start

The above command will initialize the storage area to be in /usr/local/pgsql/data, we can choose any location we want (obviously this location is for Mac, Linux users, Windows users should choose something like C:/pgsql/data or something similar)
The last lines appear in the output of the command shows us how we start the server with the above database storage. Next, we run:
$ postgres -D /usr/local/pgsql/data

Now we need to create the databases for our development/test for the sample_app. Two separate databases are needed, one for the development, and one for test. We can name them: sample_app_development, sample_app_test
To create the database, we use the command createdb and be sure that the server is still running, (leaving the Terminal window with the previous command running open)
$ createdb sample_app_development
$ createdb sample_app_test

At this point, we can modify the /config/database.yml to have the database with PostgreSQL adapter instead of SqLite adapter:

common: &common
adapter: postgresql
username: ****** (your username to postgresql database)
password: ****** (your password to postgresql database)

<<: *common
database: sample_app_development
host: localhost

<<: *common
database: sample_app_test
host: localhost

<<: *common
database: sample_app_production

You also have to modify the Gemfile to use ‘pg’ for all the environments: test, development, production.
source ‘;

gem 'rails', '3.2.3'
gem 'pg', '0.12.2'

# Bundle edge Rails instead:
# gem ‘rails’, :git => ‘git://’

group :development, :test do
gem ‘rspec-rails’, ‘2.9.0’

# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem ‘sass-rails’, ‘3.2.4’
gem ‘coffee-rails’, ‘3.2.2’
gem ‘uglifier’, ‘1.2.3’

gem ‘jquery-rails’, ‘2.0.0’

group :test do
gem ‘capybara’, ‘1.1.2’

Run this command to install the bundles:
$ bundle install

Now you can happily run the tests:
$ bundle exec rspec spec/requests/static_pages_spec.rb

Finished in 0.48331 seconds
8 examples, 0 failures

Next time when you run your rails app with rails server command, if you see this message:


could not connect to server: Connection refused
Is the server running on host “localhost” ( and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host “localhost” (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host “localhost” (fe80::1) and accepting
TCP/IP connections on port 5432?
Rails.root: /Users/pnhoang/Developer/rails_projects/sample_app

then, remember to start your server with the command:
$ postgres -D /usr/local/pgsql/data

Some notes about Heroku,first, the database.yml is overridden by Heroku so our production database configuration does not really matter to Heroku, second, when we run
$ git push heroku master

to push our code to heroku, we need to run the migration on the production database so Heroku knows about the models,
$ heroku run:detached rake db:migrate

Then we can open the site using
$ heroku open

Free online courses from Stanford and Udacity

February 27, 2012 Leave a comment

I am currently following two courses from Stanford and Udacity (online university): 

CS101 – Building a search engine

SaaS – Software as a Service

Even though CS101 is not at my level, however, I still find the course of building a search engine interesting. SaaS course is definitely a new adventure, I am currently reading the book Agile Web Development with Rails, however, joining this course allows me to learn together with a community. And have you known that they give you a certificate at the end of the course?

Besides that there are several courses available, check them out in the links to the courses above, they have references to other courses. Do you follow one of the courses? Let me know.


A bit about Key-Value Coding

I have read the documentation “Key-Value Coding Programming Guide“, but I have not found the solution for my problem: From the table of transaction objects below, I want to show in the table view, each payee with its corresponding sum amount of money:

Green Power:  $440.00

Car Loan: $750.00

General Cable: $395.00

Mortgage: $3,750.00

Animal Hospital:  $600.00

Sample transactions data

The documentation does show varieties of collection operators: @avg, @sum, @max, @min, @count, @distinctUnionOfObjects, @unionOfObjects, though what I want is not one of the operators.

I have come out with a solution that divide my problem into 2 separate steps:

  • Compute the distinct union of objects to get the payee array: Green Power, Car Loan, General Cable, Mortgage, Animal Hospital
self.payees = [self.transactions valueForKeyPath: @"@distinctUnionOfObjects.payee"]
  • On each payee of the payees array, filter the original transactions array to get only the payees with this value, and then call the valueForKeyPath with a @sum collection operator:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//(omitted code for clearance)
NSString *payee = [self.payees objectAtIndex:indexPath.row];

NSNumber *amountSum = [[self.transactions filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:@"payee = %@", payee]]
  • That’s it. Enjoy!

How to start developing Computer Vision app for the iPhone

April 29, 2011 Leave a comment

In this article, I just want to summarize the resources available on the Internet to help you start as fast as possible to develop a Computer Vision application for the iPhone.

Yoshimasa Niwa has an excellent article on using OpenCV on the iPhone, recently he has updated the project to support OpenCV 2.2.0 on iOS 4.3 and Xcode 4. If you have never downloaded the source code and project sample before, then you can just simply open the Terminal of your Mac and type:

% git clone git://

This command will get the latest master branch of the source to your current directory.

Inside the source folder, there is a sample project, open it and set the Code Signing Identity to your identity (obviously you have to register with Apple to be able to install the program on the device).

Another useful resource I have found out is the computer vision talks, a very nice tutorial will guide you through how to use OpenCV in an Objective-C project.

The Next Web has published “The 25 most influential people tweeting about augmented reality“, so if you have a Twitter account, there’s no reason to not follow all of them.

In the Voices That Matter iPhone Developers Conference Spring 2011 in Seattle, Jeff Powers(@) talked about Computer Vision and Augmented Reality on iOS,  the slides presentation is here, it’s a good place to start.

If you want to learn more about Computer Vision, there is an ebook titled: “Computer Vision: Algorithms and Applications” from Richard Szeliski, the latest draft is freely available online and you can download from the site.

Specifically about OpenCV, the “Learning OpenCV – Computer Vision with the OpenCV library” book is the best title.

Please tell me which resources you think are helpful. I will add them to the list.


Get every new post delivered to your Inbox.