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条回答
ゆ 、 Hurt°
2楼-- · 2019-01-03 00:51

Run the below command to create a migration file:

rails g migration ChangeHasedPasswordToHashedPassword

Then in the file generated in the db/migrate folder, write rename_column as below:

class ChangeOldCoulmnToNewColumn < ActiveRecord::Migration
  def change
     rename_column :table_name, :hased_password, :hashed_password
  end
end
查看更多
等我变得足够好
3楼-- · 2019-01-03 00:51

From API:

rename_column(table_name, column_name, new_column_name)

It renames a column but keeps the type and content remains same.

查看更多
唯我独甜
4楼-- · 2019-01-03 00:51

If the present data is not important for you, you can just take down your original migration using:

rake db:migrate:down VERSION='YOUR MIGRATION FILE VERSION HERE'

Without the quotes, then make changes in the original migration and run the up migration again by:

rake db:migrate
查看更多
Viruses.
5楼-- · 2019-01-03 00:52

Simply create a new migration, and in a block, use rename_column as below.

rename_column :your_table_name, :hased_password, :hashed_password
查看更多
走好不送
6楼-- · 2019-01-03 00:52

Rails 5 migration changes

eg:

rails g model Student student_name:string age:integer

if you want to change student_name column as name

Note:- if you not run rails db:migrate

You can do following steps

rails d model Student student_name:string age:integer

This will remove generated migration file, Now you can correct your column name

rails g model Student name:string age:integer

If you migrated(rails db:migrate), following options to change column name

rails g migration RemoveStudentNameFromStudent student_name:string

rails g migration AddNameToStudent name:string

查看更多
倾城 Initia
7楼-- · 2019-01-03 00:53

Open your Ruby on Rails console and enter:

ActiveRecord::Migration.rename_column :tablename, :old_column, :new_column
查看更多
登录 后发表回答