rails g migration add_x_column_to_y_table name:type name2:type2[:index]
rails g migration create_x_table name:type
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)
add_column :table_name, :relation_name_id, :integer
def change
reversible do |change|
change.up do
# go up
end
change.down do
# go down
end
end
end
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
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
class Library < ApplicationRecord
has_many :books
end
class Book < ApplicationRecord
belongs_to :library
has_many :pages
end
class Page < ApplicationRecord
belongs_to :book
end
create_join_table :categories, :products do |t|
t.index [:category_id, :product_id]
end