change column name Rails

后端 未结 4 1588
南旧
南旧 2021-02-02 10:18

I have this table:

class CreateShoes < ActiveRecord::Migration
  def change
    create_table :shoes do |t|
      t.string :name
      t.boolean :leather
              


        
4条回答
  •  礼貌的吻别
    2021-02-02 11:09

    If your intention is to rename column in table than you example migration is not making sense :)... Instead of this

    class CreateShoes < ActiveRecord::Migration
      def change
        create_table :shoes do |t|
          t.string :name
          t.boolean :leather
          t.integer :season
    
          t.timestamps null: false
        end
    
        change_table :products do |t|
          t.rename :season, :season_id
        end
    
      end
    end
    

    You just need table change migration, like this(Rails will take care rollback for your):

    class RenameSessionColumnInsideShoes < ActiveRecord::Migration
      def change
        change_table :products do |t|
          t.rename :season, :season_id
        end
      end
    end
    

    rename method on table object in rails is valid method, as you can see in Rails source code

    https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb#L582

提交回复
热议问题