Friday, April 24, 2009

Use Migration Helpers to ease your migration script

One of the purpose of rails migration script was to wrap SQL with simple ruby code. But still we need some SQL for creating foreign key or inserting some default data or updating some existing data. There is a rails plugin to solve this problem.migration_helpers provides some basic helpers for writing migration scripts.

It wraps

  1. Add/remove foreign key
  2. Insert statements
  3. update statements

Here is a sample migration that uses insert and update statement.

class CreatePosts < ActiveRecord::Migration
    def self.up
      create_table :posts do |t|
        t.string :title
        t.text :body
        t.boolean :published
    
        t.timestamps
      end
    
      insert_row('posts', :title => 'Dummy Title', :body => 'A sample post', :published => false)
      update_row('posts', :set => { :published => true }, :where => { :title => 'Dummy Title' })
    end
    
    def self.down
      drop_table :posts
    end
end
And here is a sample migration that uses foreign key reference.
class CreateComments < ActiveRecord::Migration<br />    def self.up<br />      create_table :comments do |t|<br />        t.text :body<br />        t.boolean :published<br />        t.references :post<br />    <br />        t.timestamps<br />      end<br />    <br />      add_foreign_key('comments', 'post_id', 'posts')<br />    end<br />    <br />    def self.down<br />      remove_foreign_key('comments', 'posts')<br />      drop_table :comments<br />    end<br />end

Caution:

This is really a nice plugin but I needed to modify some code to work remove_foreign_key.

In plugins/migration_helpers/lib/migration_helpers_tasks.rb file replace the remove_foreign_key with the following code

def remove_foreign_key(table, target_table, constraint_name="#{table.to_s}_#{target_table.to_s}_fkey")<br />    execute "ALTER TABLE #{table.to_s} DROP FOREIGN KEY #{constraint_name};"<br />    execute "ALTER TABLE #{table.to_s} DROP KEY #{constraint_name};"<br />end
Reference:

http://github.com/patientslikeme/migration_helpers/tree/master



No comments: