Let's say I used the following command to create a "User" model:
script/generate model User username:string
This creates the user.rb file along with the migration rb file to create the Users table. Now, I want to add an email column to my User model. What's the best way to do that? Do I do it manually and write the migration file by hand or is there a shortcut for doing it? If I write the migration by hand, do I have to name it the same way as the previous migration script (with a timestamp in front) to guarantee that it runs after the previous migration?
A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.
add_index(table_name, column_name, **options) LinkAdds a new index to the table. column_name can be a single Symbol , or an Array of Symbols. The index will be named after the table and the column name(s), unless you pass :name as an option.
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.
Don't worry about the timestamp. It will be generated automatically. You can do a
rails generate migration add_email_to_user email:string
This would automatically create a migration file which would look like this:
class AddEmailToUser < ActiveRecord::Migration
def self.up
add_column :email, :string
end
def self.down
remove_column :email
end
end
the file would have the timestamp in the format YYYYMMDDHHMMSS
(For Rails 2.1 and above) appended in front of the filename.
The Guide has information about generating migrations. If you use the rails generator, it will create correctly named files:
ruby script/generate migration AddEmailToUser email:string
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