I was working on americanwinery.com and one of my coworkers asked me about a model that they hadn't seen before. Turns out it was from the early days of the site and it was never even used in production. It was a great candidate for a little code cleanup, so I removed the model and tests and started in on the migration to remove the table.
When I write migrations I generally make a point of making them reversible, so as I was looking for the original migration to copy the structure of the table I thought it would be much easier to just call the "up" from the original migration in the "down" of the migration I was working on. It was an interesting thought, turns out it is pretty easy to do.
For example, lets say you have a migration that creates a table named articles and it looks something like this:
class CreateArticles < ActiveRecord::Migration
def self.up
create_table :articles do |t|
t.text :title, :body
t.timestamps
end
end
def self.down
drop_table :articles
end
end
A few days/months/years later you realize that you don't use that table and you decide to write a migration to get rid of it, here is what I would suggest:
class DropArticles < ActiveRecord::Migration
def self.up
CreateArticles.migrate("down")
end
def self.down
CreateArticles.migrate("up")
end
end
That is all there is to it. If you want to do a little more reading on this subject you can check out the API documentation (http://api.rubyonrails.org/classes/ActiveRecord/Migration.html)
No comments:
Post a Comment