How can I rename a database column in a Ruby on Ra

2019-01-03 00:24发布

I wrongly named a column hased_password instead of hashed_password.

How do I update the database schema, using migration to rename this column?

25条回答
可以哭但决不认输i
2楼-- · 2019-01-03 01:07

Just generate migration using command

rails g migration rename_hased_password

After that edit the migration add following line in change method

rename_column :table, :hased_password, :hashed_password

This should do the trick.

查看更多
Lonely孤独者°
3楼-- · 2019-01-03 01:08

I'm on rails 5.2, and trying to rename a column on a devise User.

the rename_column bit worked for me, but the singular :table_name threw a "User table not found" error. Plural worked for me.

rails g RenameAgentinUser

Then change migration file to this:

rename_column :users, :agent?, :agent

Where :agent? is the old column name.

查看更多
女痞
4楼-- · 2019-01-03 01:09
 def change
    rename_column :table_name, :old_column_name, :new_column_name
  end
查看更多
甜甜的少女心
5楼-- · 2019-01-03 01:12

If you need to switch column names you will need to create a placeholder to avoid a duplicate column name error. Here's an example:

class SwitchColumns < ActiveRecord::Migration
  def change
    rename_column :column_name, :x, :holder
    rename_column :column_name, :y, :x
    rename_column :column_name, :holder, :y
  end
end
查看更多
萌系小妹纸
6楼-- · 2019-01-03 01:13

Run rails g migration ChangesNameInUsers (or whatever you would like to name it)

Open the migration file that has just been generated, and add this line in the method (in between def change and end):

rename_column :table_name, :the_name_you_want_to_change, :the_new_name

Save the file, and run rake db:migrate in the console

Check out your schema.db in order to see if the name has actually changed in the database!

Hope this helps :)

查看更多
Ridiculous、
7楼-- · 2019-01-03 01:15

Generate the migration file:

rails g migration FixName

# Creates db/migrate/xxxxxxxxxx.rb

Edit the migration to do your will.

class FixName < ActiveRecord::Migration
  def change
    rename_column :table_name, :old_column, :new_column
  end
end
查看更多
登录 后发表回答