Rubynating

Saturday, August 20, 2005

Getting Rails and MySQL to play nice

Working on my first Rails application has been quite an experience -- and not the kind you think.

I've been following along with Dave Thomas' Rails book. It provides a gentle introduction to the various Rails idioms and has proven handy. Following the spirit of the instructions, I created the necessary database and tables in my MySQL instance. Chapter 6 explains that in order for Rails to communicate with a database one has to specify connection settings in the config/database.yml file. So, I provide the following

development:
adapter: mysql
database: cc_dev
host: localhost
username:
password:

I issued the command

proj_root> ruby script/generate scaffold Project Add

expecting it to create a Project model object (associated with the PROJECTS table that I had already created in MySQL) that would be accessed through the Add controller. However, after a few create messages on the console, I got the following message:

No connection could be made because the target machine actively refused it. - connect(2)

Huh? Wasn't exactly the response I was expecting. I spent a long time trying various things such as: providing a username and password, providing an IP address instead of localhost etc, etc, I reached out to Google. There I came across a post by Jared Richardson on the same topic. While my context was different it suggested a cure: comment out the line

skip-networking

in the my.cnf file. Never having played in the bowels of MySQL, I found that on WinXP, that translates to the MYSQL_INSTALL_DIR\my.ini file. Since it did not say anything about skipping networking, I added it for good measure and commented it out by prefixing the line with a # character. Still no dice.

Now it just so happens that Jared's a colleague and a friend (small world). I wrote to him about my impasse and he suggested specifying the port in the database.yml file. I was skeptical -- since the Rails crowd had been drilling in the virtues of convention over configuration; I was thinking -- surely Rails would use defaults like with most other things. Anyway, I had wasted several hours on this problem and I had nothing to lose. So I added the line

port: 3306

so, my database.yml now looks like

development:
adapter: mysql
database: cc_dev
host: localhost
port: 3306
username:
password:

Paydirt! Running the scaffold command again ran through to completion! Hope that helps you and saves you few hours.