Skip to content

Instantly share code, notes, and snippets.

@jmccartie
Created March 30, 2011 16:13
Show Gist options
  • Save jmccartie/894697 to your computer and use it in GitHub Desktop.
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
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