Home Rails migration rename index and foreign_key column
Reply: 1

Rails migration rename index and foreign_key column

Gundam Meister
1#
Gundam Meister Published in 2018-02-14 02:15:31Z

In my 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"

How can I use rails g migration to change all the "device_return" to "exchange" ?

I tired rename_table and rename_index. They didn't change t.index["device_return_id']

Thanks

Scott
2#
Scott Reply to 2018-02-14 04:10:50Z

to change the foreign key you can try

rails g migration ChangeForeignKeyForDevices

then your migration should look like this

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

then run your migration

rails db:migrate

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

rename_column(table_name, column_name, new_column_name): Renames a column but keeps the type and content.

rename_index(table_name, old_name, new_name): Renames an index.

rename_table(old_name, new_name): Renames the table called old_name to new_name.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.31509 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO