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开发者_JAVA技巧. 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?
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
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.
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
精彩评论