Search code examples
ruby-on-railsrails-migrations

Rails 5: How to make a 'migration partial' in database migrations


I have many tables using the same column names. I want to split them into partials so that I can just edit the partial to change the columns every time I re-create the database.

I've tried:

fruit migration file

class CreateFruit < ActiveRecord::Migration[5.0]
  def change
    create_table :fruits do |t|
      partial
    end
end

pet migration file

class CreatePet < ActiveRecord::Migration[5.0]
  def change
    create_table :pets do |t|
      partial
      t.string :personality
    end
end

partial file (application.rb?)

def partial
  t.string :name
  t.string :size
end

But, I'm always getting a syntax error when running migrations


Solution

  • Create a file named db/migrate/_partial_migration.rb:

    class PartialMigration
      class << self
        def call(t)
          t.string :name
          t.string :size
        end
      end
    end
    

    In your migration db/migrate/20180209112447_create_pet.rb:

    require_relative "./_partial_migration.rb"
    
    class CreatePet < ActiveRecord::Migration[5.0]
      def change
        create_table :bar do |t|
          PartialMigration.call(t)
          t.string :personality
        end
      end
    end