Garbage Burrito

Rails: Data Migrations

Rails: Data Migrations
Ben Kittrell - 08 14, 2006 @ 12:00PM
Comments: 3

I needed to add the tinyMCE WYSIWYG editor to my blog editor for obvious reasons. Previously I was using simple_format to add formatting tags post db. So now that the HTML was going to be stored in the database, I needed to retroactively format the old posts with HTML. A simple process, but how was I actually going to facilitate this? A database script? A ruby process? After working in Rails I don't like these decisions, it seems like there should be something for me to use already. Thankfully there is.

Hopefully all you Railers have heard of and are currently using migrations. They're a handy little tool for managing your database schema, and makes updating production systems a snap. For more info check out the Wiki page or DHH's slick migration demo. Up till now I had only used migrations for modifying tables, but why can't they be used for data migration? Here's an example.

class AutoFormatBlog < ActiveRecord::Migration
  extend ActionView::Helpers::TextHelper
  extend ActionView::Helpers::TagHelper

  def self.up
    entries = Entry.find(:all)
    for entry in entries
      entry.content = simple_format(entry.content)
      entry.save
    end
  end

  def self.down
    entries = Entry.find(:all)
    for entry in entries
      entry.content = strip_tags(entry.content)
      entry.save
    end
  end
end

As you can see this is very simple. The 'up' method simply iterates through all of the blog entries and uses simple_format to add HTML tags. The 'down' method is used to undo this by calling strip_tags. This is one of the major benefits of using migrations is that you can write and test your 'undo' ahead of time.

So you get a standardized method of migrating data, built-in undo, and access to active record and other ruby goodies.

Comments: 3

Comments

1. rheaghen - 08 17, 2006 @ 06:40AM

sounds highly useful! I admire your courage and pioneering spirit!

2. Lan Wirelles - 05 23, 2008 @ 11:51AM

the code is correct !

3. impresora - 05 27, 2008 @ 09:32PM

very cool

Post a Comment




powered by : Doodlekit Online Free Website Builder : developed by : Doodlebit™ Website Company