Friday, August 18, 2006

Ruby/Rails tricks and tips with ActiveRecord

I had a simple problem definition:
  • Write a installer application in rails which will take database username, password and database name
  • Creates brand new database
  • Populate the database with schema and reference data.
  • Updates database.yml file
  • Reinitialize the rails activerecord connection context, so that user does not have to restart the application
This is how I solved it. few steps , hopefully this will be usefull for other ppl who wants to do something similar.


# Create new database

ActiveRecord::Base.connection.create_database("rex_boy") #rex_boy new database name.

# Load new database with schema and data.
.........This you can do either by using writing Rake migrate tasks or manually write SQL's to load the schema and data, 1000's of ways to do this. I did using creating using migrations and invoking rake command from rails.


# Read and update the database.yml file with newly created database

## Read the Yml and update with new database name
@config = YAML::load(File.open("#{RAILS_ROOT}/config/database.yml")) @config['development']['database']= "rex_boy"

## Now update the yml file back. basically write the database.yml back from @config object
File.open( "#{RAILS_ROOT}/config/database.yml", 'w' ) do |f| f << @config.to_yaml

# Now the interesting part to reintialize ActiveRecord connection context without restarting the server (Apache or WEBrick or Lighttpd..)

ActiveRecord::Base.configurations = @config ActiveRecord::Base.establish_connection ActiveRecord::Base.connection



This should get you very fancy in terms of building rails based installer application.

2 comments:

Anonymous said...

I've been working on something similar and was going down the same path as you, however, I ran into problems calling the create_database method. I kept getting an error about the database not existing (which is true). I figured I was missing an authentication step, but am not having luck finding out how to do that. How do you tell mysql that you have the rights to create a database?

Rajesh Shetty said...

Aparently You do not need to tell MySQL that you need a rights, because MySQL does not care as long as you provide root username/password or whichever id you have to access the MySQL and your custom databases.

I'm doing the similar thing in my OpenAppDotOrg Toolkit's installer module.
So you need to login as root and then create database like

ActiveRecord::Base.connection.create_database(dbname)

You can download the version either from sourceforge (http://sourceforge.net/projects/openappdotorg)or check out the project from Google code (code.google.com/p/openappdotorg)