Rails: Data Migrations
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.




Post a Comment