Skip to content

Instantly share code, notes, and snippets.

@petitJAM
Last active March 11, 2019 19:26
Show Gist options
  • Save petitJAM/09ce9c3d5b07372f55b315d23fcfc2a9 to your computer and use it in GitHub Desktop.
Save petitJAM/09ce9c3d5b07372f55b315d23fcfc2a9 to your computer and use it in GitHub Desktop.
Rails Migration Cheat Sheet

Rails Migration Cheat Sheet

rails generate migration

rails g migration add_x_column_to_y_table name:type name2:type2[:index]

rails g migration create_x_table name:type

Columns

add_column(table_name, column_name, type, options = {})

remove_column(table_name, column_name, type = nil, options = {}) (Rails 4+)

remove_column(table_name, column_name) (Rails < 4)

rename_column(table_name, old_column_name, new_column_name)

add_reference(table_name, referenced_table_name, options = {index: boolean, foreign_key: boolean}

change_column_default(table_name, column_name, default) (not reversible)

change_column_default(table_name, column_name, from: old_default, to: new_default) (reversible)

change_column_null(table_name, column_name, null, default = nil) (fourth argument does not set column default)

Adding a has_one relation

add_column :table_name, :relation_name_id, :integer

Reversible

def change
  reversible do |change|
    change.up do
      # go up
    end
    
    change.down do
      # go down
    end
  end
end

Tables

create_table :companies do |t|
  t.string :name, null: false
  
  t.references :table_name_singular, index: true, foreign_key: true, null: false
  
  t.attachment :image # Paperclip
  
  t.timestamps
end
change_table :companies do |t|
  t.string :owner, null: false
end

Data

Define any classes you use inside your migration to prevent future app changes from breaking the migration.

class ChangeColumnData < ActiveRecord::Migration
  class Product < ActiveRecord::Base
  end
  
  def change
    Product.where(whatever: nil).update_all(other_whatever: 4)
    add_column :product, :who_cares, :boolean
  end
end

Misc

class Library < ApplicationRecord
  has_many :books
end

class Book < ApplicationRecord
  belongs_to :library
  has_many :pages
end

class Page < ApplicationRecord
  belongs_to :book
end

has_and_belongs_to_many

create_join_table :categories, :products do |t|
  t.index [:category_id, :product_id]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment