Rails migrations are an extremely handy way of capturing changes to your database and rolling them back if they are incorrect.
Manipulating or querying a database is a pretty useful tool and ActiveRecord turns your tables into objects so I looked into how to access these features outside of a Rails environment.
I wanted to be able to either specify the database connection details directly in the script if I was running it outside of a Rails application, or to be able to bind into the Rails application's
database.yml database configuration file.
To run it as a standalone script with the database details described inside the script run:
ruby play_with_the_database.rbTo run it within the context of a Rails application place the script inside a new directory called
ruby play_with_the_database.rb developmentIf you want to run the above script against the production database run:
ruby play_with_the_database.rb productionI'll show you the ruby code that I came up with and then explain the important bits below.
database_type = ARGV
database_type = 'custom'
database_yaml = <<-YAML
# if you have a Rails project then place your scripts in db/script
database_yaml = IO.read('../../config/database.yml')
class MyTable < ActiveRecord::Base; set_table_name :my_table; end
class Script < ActiveRecord::Migration
execute('update my_table set updated = true')
databases = YAML::load(database_yaml)
database_type- this is the RAILS_ENV that you want to run the database script against if you are running within a Rails application, it's empty at the start of the script and set to the value that you pass as the first argument on the command line. If an argument is present it looks up that value in the database.yml file otherwise it uses the inlined database connection details within the script.
class MyTable- any ActiveRecord object definitions go here allowing you to map objects to tables.
def self.run- Place the guts of your database script within this method so that it has access to all the ActiveRecord objects as well as any methods that migrations have access to (such as
execute, create_table, add_column, remove_index, etc.).
Technorati Tags: Ruby, Script, Rails, ActiveRecord, Migration, Dave Thomas, Andrew Beacock