Created
March 30, 2011 16:13
-
-
Save jmccartie/894697 to your computer and use it in GitHub Desktop.
Migrating from a has_one relationship to a has_and_belongs_to_many
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RemoveCategoryIdFromItem < ActiveRecord::Migration | |
def self.up | |
# Migrate items from has_many | |
Item.all.each do |item| | |
CategoriesItems.create(:item_id => item.id, :category_id => item.category_id) | |
end | |
remove_column :items, :category_id | |
end | |
def self.down | |
add_column :items, :category_id, :integer | |
# Migrate items to has_many | |
CategoriesItems.all.each do |record| | |
item = Item.find(record.item_id) | |
item.category_id = record.category_id if item.category_id.nil? | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment