Rails迁移重命名索引和foreign_key列

时间:2018-02-14 02:15:31

标签: ruby-on-rails database activerecord migration schema

在我的schema.rb中,

create_table "devices", force: :cascade do |t|
    t.string "uuid"
    t.bigint "device_return_id"
    t.index ["device_return_id"], name: "index_devices_on_device_return_id"
end

create_table "device_returns", force: :cascade do |t|
  t.string "code"
  t.datetime "returned_at"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

add_foreign_key "devices", "device_returns", column: "device_return_id"

如何使用rails g migration更改所有" device_return"到"交换" ?

我累了rename_table和rename_index。他们没有改变t.index [" device_return_id']

由于

1 个答案:

答案 0 :(得分:0)

更改您可以尝试的外键

rails g migration ChangeForeignKeyForDevices

那么你的迁移应该是这样的

class ChangeForeignKeyForDevices < ActiveRecord::Migration
   def change
      rename_column :device_returns, :old_column_name, :new_column_name
   end
end

然后运行迁移

rails db:migrate

http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

rename_column(table_name,column_name,new_column_name):重命名列但保留类型和内容。

rename_index(table_name,old_name,new_name):重命名索引。

rename_table(old_name,new_name):将名为old_name的表重命名为new_name。