Rails – How to Change Column Name

databaseruby-on-rails

I have this table:

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
  end
end

the 'season' column should be called 'season_id'. I know that I have to write 't.rename :season, :season_id' as explained in http://edgeguides.rubyonrails.org/active_record_migrations.html#column-modifiers but I don't manage to find the right syntax. Should it be?

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

Doesn't work. Anything I have to do in the Mac console? Thanks!

Best Answer

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.