Home

Access A Deleted Class In A Rails Migration

Sometimes you need to get to a class that you have deleted or renamed within a migration file. Here's how you do it.

There are times when you need to get to a class to be able to run a migration, but that class doesn't exist anymore.

This has happened to me a few times. Most recently, I was working on a project using single table inheritance. I had to rename one of the subclasses. But I also needed to make sure the data that already existed in production migrated effectively. In other words, I wanted that class for just a second -- to run a quick query and then be done.

Note: There are other ways to get around my specific STI case -- I'm using it as a demonstration.

01: The Ugly Way

In the past, I had left the class around until I could run the migration in production. And then I'd remove it for the following release.

I've never liked this approach.

02: The Quicker Way

Instead, there's a nice and easy way to get around this. You can define the class within the migration, like so:

class TheNameOfMyMigration < ActiveRecord::Migration

class MyDeletedClass < ActiveRecord::Base
end

def change
# migration code here
end

end

Now, if you need to get to some of the methods that class had used in the migration code, then you'll either need to use Method 01 above, or you'll want to include that code in the redefined class within the migration. (Or you'll need to be a little more clever if you don't want to redefine the class.)

Let's Connect

Keep Reading

How To Use Paper Trail As An Activity Feed

That whole killing two birds with one stone approach might just work in using PaperTrail as an activity log, at least in simpler projects.

Jun 15, 2015

Related Content (without metadata) in Rails using tf-idf

Sometimes metadata isn't available. Other times you don't want to rely on it. Here's a method for finding related content using term frequency / inverse document frequency.

Oct 12, 2014

Why I Don't Use has_and_belongs_to_many in Rails

The magic of Rails makes it easy to create simple many-to-many relationships, but I almost never use it, and here's why.

Mar 31, 2015