cirandas.net

ref: master

db/migrate/20110520150544_remove_categories_with_invalid_type.rb


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class RemoveCategoriesWithInvalidType < ActiveRecord::Migration

  def self.remove_invalid(category)
    if category.class != ProductCategory && !category.class.ancestors.include?(ProductCategory)
      execute("update categories set type='ProductCategory' where id=#{category.id}")
    else
      category.children.map { |child| remove_invalid(child) }
    end
  end

  def self.up
    select_all("SELECT id from categories WHERE type = 'ProductCategory'").each do |product_category|
      category = ProductCategory.find(product_category['id'])
      remove_invalid(category)
    end
  end

  def self.down
    say "this migration can't be reverted"
  end
end