How to write conditional migrations in rails?

前端 未结 4 634
悲&欢浪女
悲&欢浪女 2020-12-30 01:14

I am looking for ways to write migrations in rails that can be executed against the database many times without failing.

For instance let say I have this migration:

4条回答
  •  盖世英雄少女心
    2020-12-30 01:17

    You can do something like this:

    class AddUrlToProfile < ActiveRecord::Migration
      def self.up
        Profile.reset_column_information
        add_column(:profile, :url, :string) unless Profile.column_names.include?('url')
    
      end
    
      def self.down
        Profile.reset_column_information
        remove_column(:profile, :url) if Profile.column_names.include?('url')
      end
    end
    

    This will reset the column information before it begins - making sure that the Profile model has the up-to-date column information from the actual table. It will then only add the column if it doesn't exist. The same thing happens for the down function, but it only removes the column if it exists.

    If you have multiple use cases for this you could factor the code out into a function and re-use that in your migrations.

提交回复
热议问题