Rails migration for change column

后端 未结 9 1097
一个人的身影
一个人的身影 2020-11-28 17:24

We have script/generate migration add_fieldname_to_tablename fieldname:datatype syntax for adding new columns to a model.

On the same line, do we have a

9条回答
  •  天命终不由人
    2020-11-28 18:10

    This is all assuming that the datatype of the column has an implicit conversion for any existing data. I've run into several situations where the existing data, let's say a String can be implicitly converted into the new datatype, let's say Date.

    In this situation, it's helpful to know you can create migrations with data conversions. Personally, I like putting these in my model file, and then removing them after all database schemas have been migrated and are stable.

    /app/models/table.rb
      ...
      def string_to_date
        update(new_date_field: date_field.to_date)
      end
    
      def date_to_string
        update(old_date_field: date_field.to_s)
      end
      ...
    
        def up
            # Add column to store converted data
            add_column :table_name, :new_date_field, :date
            # Update the all resources
            Table.all.each(&:string_to_date)
            # Remove old column
            remove_column :table_name, :date_field
            # Rename new column
            rename_column :table_name, :new_date_field, :date_field
        end
    
        # Reversed steps does allow for migration rollback
        def down
            add_column :table_name, :old_date_field, :string
            Table.all.each(&:date_to_string)
            remove_column :table_name, :date_field
            rename_column :table_name, :old_date_field, :date_field
        end
    

提交回复
热议问题