Reversible migration for change_column_default from not having any default in Rails

前端 未结 7 2202
青春惊慌失措
青春惊慌失措 2021-02-18 21:34

The Rails guides to active record migrations says that you can do

change_column_default :products, :approved, from: true, to: false

I\'ve got a

7条回答
  •  天涯浪人
    2021-02-18 22:30

    First of all as Jonathan Allard said the from and to are not in the method source which means that the change_column_default doesn't accepts it. It is simply like this:

    def sum(a)
      return a
    end
    

    Now if you try and pass two variables to it like sum(a, b) or anything it will not accept that right. This what you are trying to do above using from and to.

    Now the correct syntax of this is:

    change_column_default(:people, :height, 0)
    

    The method doesn't accepts from and to(as it is defined as such, even if they are hash keys, if the method doesn't uses that key value pair anywhere then it is of no use to it) and if it is a new column the obviously it will have default value nil(if not set before) and suppose if the column height if of type integer and you give it default value a it will store 0 as the default value (not 100% sure but have tried doing this from rails console). It doesn't matters to rails what the default value currently is, it just needs the new default value. So if the current default value be 0 and you set it to nil rails will not complaint. It is your database and you wish what to do with it. Just if the database interrupts it if you are doing something wrong like assigning string to boolean then it will obviously throw error.

    Now once this migration has ran then it will set the default value to 0 now rails doesn't know what the previous default value was. As it is gone and it has not store that anywhere. So that is why change_column_default is a irreversible migration. And if you try to roll it back it gives you ActiveRecord::IrreversibleMigration: ActiveRecord::IrreversibleMigration in case of change method. Means when you have used:

    def change
      change_column_default(:people, :height, 0)
    end
    

    So that is why for this kind of migrations we use the method up and down:

    def up
      change_column_default(:people, :height, 0)
    end
    
    def down
      change_column_default(:people, :height, nil)
    end
    

    Hope this helps.

提交回复
热议问题