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?
You can use the change method with the rename_column definition in your migrations files to update a single column name in your database.
To check for status, run rails db:migrate:status . Then you'll have a good view of the migrations you want to remove. Then, run rails db:rollback to revert the changes one by one. After doing so, you can check the status again to be fully confident.
Migrations are a convenient way to alter your database schema over time in a consistent way. They use a Ruby DSL so that you don't have to write SQL by hand, allowing your schema and changes to be database independent. You can think of each migration as being a new 'version' of the database.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With