change column name Rails

后端 未结 4 1590
南旧
南旧 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:02

    If your branch has been pushed to production then one probably needs to add the new migration by running the following command:

    rails g migration RenameSeasonColumnNameToShoes

    and if it hasn't been pushed to production or you have to currently make changes to your branch only, then do:

    bundle exec rake db:rollback

    Then make changes to your migration file inside /db/migrate/<your_migration_file_name>

    Then in your migration file, using rename_column do as follows:

    class RenameSeasonColumnNameToShoes < ActiveRecord::Migration
      def change
          rename_column :shoes, :season, :season_id
      end
    end
    

    and then do

    bundle exec rake db:migrate db:test:prepare

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-02 11:11

    Either fix your migration and do

    rake db:rollback db:migrate
    

    or make another migration like so:

    rename_column :shoes, :season, :season_id if column_exists?(:shoes, :season) && !column_exists?(:shoes, :season_id)
    

    and then do

    rake db:migrate
    
    0 讨论(0)
  • 2021-02-02 11:16

    Run in your console:

    $ rails g migration rename_season_to_season_id
    

    Now file db/migrate/TIMESTAMP_rename_season_to_season_id.rb contains following:

    class RenameSeasonToSeasonId < ActiveRecord::Migration
      def change
      end
    end
    

    Modify it as follows:

    class RenameSeasonToSeasonId < ActiveRecord::Migration
      def change
        rename_column :shoes, :season, :season_id
      end
    end
    

    Then run $ rake db:migrate in console.

    0 讨论(0)
提交回复
热议问题