One time change model attribute (column name) in Ruby on Rails

天大地大妈咪最大 提交于 2020-01-13 02:14:50

问题


I created a model with an attribute "name" but I want to change it to "username". Everything I've read about database migrations involves creating a class or some complicated stuff. All I want to do is the equivalent of "UPDATE TABLE" in SQL. How do you run a one-time database migration to change this? I'm guessing it'd involve rails console and then some command?


回答1:


First:

rails g migration rename_name_column_to_username

Then in the generated rename_name_column_to_username.rb migration file:

class RenameNameColumnToUsername < ActiveRecord::Migration
  def self.up
    rename_column :users, :name, :username
  end

  def self.down
    rename_column :users, :username, :name
  end
end

And then rake db:migrate




回答2:


If you haven't committed the code that originally created the "name" column, you can just go in to the old migration file that created that column and change name to username and then regenerate the schema.

But if you have committed the code, you should create a separate migration file that renames name to username.

This is important to keep track of the versioning of your database. So you should never really use manual SQL (ALTER TABLE ...) to change the schema.




回答3:


Run rails g migration RenameNameToUsername, which will create a new file in db/migrate.

Open that file, and add this into the self.up section:

rename_column :tablename, :name, :username

Then run rake db:migrate



来源:https://stackoverflow.com/questions/6245115/one-time-change-model-attribute-column-name-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!