tng-rails-code-snippets-3.md#
change_table(table_name, options = {}) public Active Record Migrations
Adding a column to an existing table in a Rails migration#
rails generate migration add_email_to_users email:string
rails db:migrate
> rails db:rollback
> $rake db:migrate:redo # This will roll back the last migration and migrate it again.
> rake db:schema:load # if you make changes in the schema.rb file (this wipes all your data)
You could rollback the last migration by
rake db:rollback STEP=1
or rollback this specific migration by
rake db:migrate:down VERSION=<YYYYMMDDHHMMSS>
> and edit the file, then run rake db:mirgate again.
sample#
class CreateUsers < ActiveRecord::Migration
def self.up
add_column :users, :email, :string
create_table :users do |t|
t.string :username
t.string :email
t.string :crypted_password
t.string :password_salt
t.string :persistence_token
t.timestamps
end
end
def self.down
drop_table :users
end
end
also#
> You also can use special change_table method in the migration for adding new columns:
change_table(:users) do |t|
t.column :email, :string
end
You can also add column to a specific position using before column or after column like:#
> rails generate migration add_dob_to_customer dob:date
>
> The migration file will generate the following code except after: :email. you need to add after: :email or before: :email
class AddDobToCustomer < ActiveRecord::Migration[5.2]
def change
add_column :customers, :dob, :date, after: :email
end
end