JJD
JJD

Reputation: 51864

How to inherit from another Rails migration?

I have a Rails migration for a simple User model:

class Users < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name, :default => :null
      t.float :weight
      t.datetime :recorded_at
      t.timestamps
    end
  end
end

I would like to have a second table for the history of the user. It should have the same columns but another name, obviously. Also it should reference the user table.

require_relative '20130718143019_create_history.rb'    

class History < Users
  def change
    create_table :history do |t|
      t.references :user
      # ...?
    end
  end
end

How can use inheritence to avoid copying all the migration configuration?

Upvotes: 2

Views: 454

Answers (1)

JJD
JJD

Reputation: 51864

After leaving the keyboard tomatoes fell off my eyes and it was clear how I can set this up:

class Users < ActiveRecord::Migration
  def change
    create_table :users do |t|
      prepare_columns(t)
    end
  end

  protected

  def prepare_columns(t)
    t.string :name, :default => :null
    t.float :weight
    t.datetime :recorded_at
    t.timestamps
  end

end

...

require_relative '20130718143019_create_history.rb'    

class History < Users
  def change
    create_table :history do |t|
      t.references :user
      prepare_columns(t)
    end
  end
end

Upvotes: 1

Related Questions