Sha256: f82c4a230144fbf1665cf423e05fd8d7bfa147b640ebd55bc39978521b25518d

Contents?: true

Size: 1.82 KB

Versions: 6

Compression:

Stored size: 1.82 KB

Contents

class AddCategorizationModel < ActiveRecord::Migration
  class ArticlesCategory < ActiveRecord::Base
    include BareMigration
  end

  class Categorization < ActiveRecord::Base
    include BareMigration
  end

  def self.up
    create_table :categorizations do |t|
      t.column :article_id, :integer
      t.column :category_id, :integer
      t.column :is_primary, :boolean
    end

    unless $schema_generator
      # You need test if ArticlesCategory object exist because if
      # exception raise even rescue in migration and migration failed and stop
      # :(
      if table_exists? :articles_categories
        ArticlesCategory.all.each do |ac|
          Categorization.create!(:article_id => ac.article_id,
                                 :category_id => ac.category_id,
                                 :is_primary => (ac.is_primary == 1))
        end
        drop_table :articles_categories
      end
    end
    # Adds the article category to the first post if and only if generating the schema
    if User.count.zero?
      puts "Adding category to default article"
      article = Article.find(:first)
      category = Category.find(:first)
      Categorization.create!(:article_id => article.id,
                             :category_id => category.id,
                             :is_primary => 1)
    end
  end

  def self.down
    create_table :articles_categories, :id => false do |t|
      t.column :article_id, :integer
      t.column :category_id, :integer
      t.column :is_primary, :integer
    end

    unless $schema_generator
      Categorization.find(:all).each do |c|
        ArticlesCategory.create!(:article_id => c.article_id,
                                 :category_id => c.category_id,
                                 :is_primary => c.is_primary ? 1 : 0)
      end
    end

    drop_table :categorizations
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
typo-5.5 db/migrate/057_add_categorization_model.rb
typo-5.4.4 db/migrate/057_add_categorization_model.rb
typo-5.4.3 db/migrate/057_add_categorization_model.rb
typo-5.4.2 db/migrate/057_add_categorization_model.rb
typo-5.4.1 db/migrate/057_add_categorization_model.rb
typo-5.4 db/migrate/057_add_categorization_model.rb