Overriding class methods for migrations, a follow-up
I realized I left one important point out from my previous post. I’m sure a few of you may have already picked up on this as well. When you override the class in the migration, you can add in whatever methods you would like the migration to use. We’ll use the same example as before:
004_add_live_pages.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class AddLivePages < ActiveRecord::Migration # Say for instance the Page.rb model has 20 instance methods in it # that we don't want to have affect our migration, but there is # 1 method we want to use below class Page < ActiveRecord::Base # The method 'stripped_name' below is an extension # of the String class def set_permalink self.update_attribute( :permalink, "#{self.id}-#{self.stripped_name}" ) if self.permalink.blank? end end def self.up page = Page.create( :name => "About", :body => "Write your about page content here.", ) page.set_permalink end def self.down end end |
Ta da! Now we can use the ‘set_permalink’ instance method anywhere inside our migration

Sorry, comments are closed for this article.