Rails migrations - change_column with type conversion

后端 未结 4 1440
深忆病人
深忆病人 2020-12-04 17:36

I already google\'d aroung a little bit and seems there\'s no satisfying answer for my problem.

I have a table with column of type string. I\'d like to run following

4条回答
  •  难免孤独
    2020-12-04 18:21

    Not all databases allow changing of column type, the generally taken approach is to add a new column of the desired type, bring any data across, remove the old column and rename the new one.

    add_column :users, :smoking_tmp, :boolean
    
    User.reset_column_information # make the new column available to model methods
    User.all.each do |user|
      user.smoking_tmp = user.smoking == 1 ? true : false # If smoking was an int, for example
      user.save
    end
    
    # OR as an update all call, set a default of false on the new column then update all to true if appropriate.
    User.where(:smoking => 1).update_all(:smoking_tmp = true) 
    
    remove_column :users, :smoking
    rename_column :users, :smoking_tmp, :smoking
    

提交回复
热议问题