Skip to content

Instantly share code, notes, and snippets.

@dubilla
Forked from datwright/gist:1082717
Created January 2, 2016 18:29
Show Gist options
  • Save dubilla/c111f2fd832236e33d45 to your computer and use it in GitHub Desktop.
Save dubilla/c111f2fd832236e33d45 to your computer and use it in GitHub Desktop.
Rails Migrations Cheat sheet
# Migration generator shortcuts.
# rails generate migration MyNewMigration
# rails generate migration add_fieldname_to_tablename fieldname:string
# rails generate model Product name:string description:text
# The set of available column types [:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean]
# A migration is a subclass of ActiveRecord::Migration. You must implement the "up" and "down" (revert) methods.
# These are the handy methods available to a Migration:
create_table
change_table
drop_table
add_column
change_column
rename_column
remove_column
add_index
remove_index
execute # (use this method to compose and execute raw sql -- note that foreign key constraints aren't included in the functions above, so that's something you'd do with 'execute')
# See http://api.rubyonrails.org/classes/ActiveRecord/Migration.html for the params for these functions.
# Here's how the add_column function works, note the applicable types for columns.
# add_column(table_name, column_name, type, options): Adds a new column to the table called table_name named column_name specified to be one of the following types: :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean. A default value can be specified by passing an options hash like { :default => 11 }. Other options include :limit and :null (e.g. { :limit => 50, :null => false })
# If your migration can't be reverted, throw the ActiveRecord::IrreversibleMigration exception in your "down" method.
# If you want to both add a new column and populate/use that column in the same migration, you have to use the reset_column_information function. See below:
class AddPeopleSalary < ActiveRecord::Migration
def self.up
add_column :people, :salary, :integer
Person.reset_column_information
Person.find(:all).each do |p|
p.update_attribute :salary, SalaryCalculator.compute(p)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment