How do you deal with breaking changes in Rails migration?

Let's say I start with this model:

class Location < ActiveRecord::Base
  attr_accessible :company_name, :location_name
end

Now I want to reorganize one of the values ​​into a related model.

class CreateCompanies < ActiveRecord::Migration
  def self.up
    create_table :companies do |t|
      t.string :name, :null => false
      t.timestamps
    end

    add_column :locations, :company_id, :integer, :null => false
  end

  def self.down
    drop_table :companies
    remove_column :locations, :company_id
  end
end

class Location < ActiveRecord::Base
  attr_accessible :location_name
  belongs_to :company
end

class Company < ActiveRecord::Base
  has_many :locations
end

All this works great during development, as I do everything in a row; but if I try to install this in my intermediate environment, I will have problems.

The problem is that since my code has already changed to reflect the migration, it causes the environment to crash when trying to migrate.

Has anyone else dealt with this problem? Am I resigned to divide my deployment into several phases?

, ; , . . @noodl , , - . .

+3
2

, , , . .

, , , , ​​ .

. , , ActiveRecord::Base, , , , , , ruby SQL.

#20110111193815_stop_writing_fragile_migrations.rb
class StopWritingFragileMigrations < ActiveRecord::Migration
  class ModelInNeedOfMigrating < ActiveRecord::Base
    def matches_business_rule?
      #logic copied from model when I created the migration
    end
  end
  def self.up
    add_column :model_in_need_of_migrating, :fancy_flag, :boolean, :default => false

    #do some transform which would be difficult for me to do in SQL
    ModelInNeedOfMigrating.all.each do |model|
      model.update_attributes! :fancy_flag => true if model.created_at.cwday == 1 && model.matches_business_rule?
      #...
    end
  end

  def self.down
    #undo that transformation as necessary
    #...
  end
end
+9

? , ( ).

drop_table remove_column self.down .

0

Source: https://habr.com/ru/post/1785105/


All Articles