更改列名称Rails

时间:2016-01-14 17:55:40

标签: ruby-on-rails database

我有这张桌子:

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

赛季&#39;列应该被称为&#39; season_id&#39;。我知道我必须写下季节:season_id&#39;正如http://edgeguides.rubyonrails.org/active_record_migrations.html#column-modifiers中所述,但我没有设法找到正确的语法。应该是吗?

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

不起作用。我在Mac控制台中需要做什么?谢谢!

4 个答案:

答案 0 :(得分:56)

在您的控制台中运行:

$ rails g migration rename_season_to_season_id

现在文件db/migrate/TIMESTAMP_rename_season_to_season_id.rb包含以下内容:

class RenameSeasonToSeasonId < ActiveRecord::Migration
  def change
  end
end

按如下方式修改:

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

然后在控制台中运行$ rake db:migrate

答案 1 :(得分:4)

修复迁移并执行

rake db:rollback db:migrate

或进行另一次迁移:

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

然后再做

rake db:migrate

答案 2 :(得分:1)

如果您的分支已经推送到生产环境,则可能需要通过运行以下命令来添加新的迁移:

rails g migration RenameSeasonColumnNameToShoes

,如果尚未将其推送到生产环境,或者您当前只需要对分支机构进行更改,则请执行以下操作:

bundle exec rake db:rollback

然后在/db/migrate/<your_migration_file_name>内更改迁移文件

然后使用rename_column在迁移文件中执行以下操作:

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

然后做

bundle exec rake db:migrate db:test:prepare

答案 3 :(得分:0)

如果您打算重命名表中的列而不是示例迁移没有意义:)...而不是这个

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

你只需要表格更改迁移,就像这样(Rails会照顾你的回滚):

class RenameSessionColumnInsideShoes < ActiveRecord::Migration
  def change
    change_table :products do |t|
      t.rename :season, :season_id
    end
  end
end
rails中的表对象上的

rename方法是有效的方法,正如您在Rails源代码中看到的那样

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