Migrations
Location
db/migrate/
- Should be prefix with the timestamp of the creation.
20170501123345_my_migration.rb
Best pratices in Migrations
A migration is a one shot operation on the database. You must follow this recommendations:
- Default values for booleans: boolean should always be
true
orfalse
- Indexes: think about the fields you will query in the future and add indexes to them. It's critical for performances and you must have indexes for foreign keys (
user_id
,post_id
, etc). - Rollback: all migrations should be reversible. Create a
#up
and#down
method on each migration. - Never edit a migration after push: people in your team will pull your code and run the latest migrations. The code pushed will also be deployed to production. If you did a mistake or forgot something in your migration (like indexes or default values), you have to create another migration and push it.
- Data operations: If you need to migrate data structure in your database, use a migration. Confirm with the team that you can apply it and everything is ready to handle this data migration.
Code
class MyMigrationnameHere < ActiveRecord::Migration
def change
add_column :events, :refresh_interval, :integer
add_column :events, :admin, :boolean, default: false
# Normal index
add_column :users, :project_id, :integer
add_index :users, :project_id
# Combine indexes:
add_index :users, [:kind, :created_at]
# Using GIST or GIN (PostgreSQL)
add_index :users, :tags, using :gin
add_index :users, :tags, using :gist
end
end