SlideShare a Scribd company logo
1 of 1
Download to read offline
Cheatsheet • Migrations
                                                      Column Types1                                                                                  Shortcut methods²
               ‹db2           ‹mysql         ‹openbase ‹Oracle            ‹postgresql ‹sqlite        ‹sqlserver ‹Sybase               t.column          t.change              t.rename
:binary        blob(32768)    blob           object       blob            bytea       blob           image          image             t.remove          t.change_default      t.references
:boolean       decimal(1)     tinyint(1)     boolean      number(1)       boolean     boolean        bit            bit               t.remove_ref-     t.belongs_to          t.remove_be-
:date          date           date           date         date            date        date           datetime       datetime          erences                                 longs_to
:datetime      timestamp      datetime       datetime     date            timestamp   datetime       datetime       datetime          t.timestamps      t.index               t.remove_index
:decimal       decimal        decimal        decimal      decimal         decimal     decimal        decimal        decimal
               float          float          float        number          float       float          float(8)       float(8)
:float
:integer       int            int(11)        integer      number(38)      integer     integer        int            int                              directory structure
:string        varchar(255)   varchar(255)   char(4096)   varchar2(255)   *           varchar(255)   varchar(255)   varchar(255)
                                                                                                                                          db
:text          clob(32768)    text           text         clob            text        text           text           text
                                                                          time        datetime       datetime       time                       schema.rb
:time          time           time           time         date
:timestamp     timestamp      datetime       timestamp    date            timestamp   datetime       datetime       timestamp                      migrate
                                                                                                                                                       20080812205401_create_products.rb
                                      Table methods                                                                                                    20080812215015_add_data.rb
‹change_table
Provides a block that enables you to alter columns on an existing table using various shortcut
methods²                                                                                                                            example_migration.rb
  change_table :table_name, {options} do |t|                                                            class CreateCustomers < ActiveRecord::Migration
    t.change :column_name, :new_column_type                                                               def self.up
    t.remove :column_name                                                                                   create_table :customers, :primary_key => :customer_id, :options =>
  end                                                                                                   "auto_increment = 10000" do |t|
‹create_table                                                                                                 t.integer :customer_id
                                                                                                              t.string :name,         :limit   => 30, :null => false
Creates a table on the database. Creates a table called :table_name and makes the table                       t.integer :age
object available to a block that can then add columns to it by specifying column_types1 or                    t.boolean :premium,     :default => 0
utilising shortcut methods² such as using belongs_to to specify foreign keys.                                 t.binary :photo,        :limit   => 2.megabytes
   create_table :table_name, {table_options} do |t|                                                           t.timestamps
       t.string :name, {column_options}                                                                       t.text :notes,          :default => "No notes recorded"
  end                                                                                                       end
                                                                                                            add_column :customers, :surname, :string,    :limit => 50
                                       {table_options}                                                      add_column :orders,    :price,    :decimal, :precision => 8,
:force       true or false if true, forces drop of an existing table of the same name                   :scale => 2
                           before creation the new one                                                      Customer.create :name => "David", :surname => "Smith", :age =>
                                                                                                        "32", :premium => "1", :notes => "One of our top customers!"
:temporary   true or false if true, creates a temporary table, one that goes away when                     end
                           the application disconnects from the database                                def self.down
:id          true or false if false, defines a table with no primary key, for example                       drop_table :customers
                           when you need to define a join table                                           end
:primary_key :symbol       overrides the default name of :id for the primary column.                    end
                           Use this to specify the name of the column in the database
                           that Rails will use to store the primary key
:options     "string"      pass raw options to your underlying database, e.g. auto_in-                                                         Fixtures
                           crement = 10000. Note that passing options will cause you
                           to lose the default ENGINE=InnoDB statement                                 Fixtures contain data which can be loaded into your database using migrations. For
                                                                                                       example, to load data into a table named customers...
‹drop_table                                                                                            1. Create a directory, db/migrate/data
Destroys the specified table.                                                                          2. Create a file, customers.yml, inside db/migrate/data
  drop_table :table_name                                                                               3. Generate a new migration file: ruby script/generate migration load_cus-
                                                                                                       tomers_data
‹rename_table                                                                                          4. Edit it to load data from the customers.yml file into your customers table
Renames the specified table.                                                                           ‹customers.yml ‹migration.rb
  rename_table :old_table_name, :new_table_name                                                         melissa:        require 'active_record/fixtures'
                                                                                                          name: Melissa class LoadCustomerData
                                   Column methods                                                         age: 18        def self.up
                                                                                                                          down
‹add_column                                                                                             david:            directory = File.join(File.dirname(__FILE__),
                                                                                                          name: David   "data")
Creates a new column on the specified table.                                                              age: 23         Fixtures.create_fixtures(directory, "customers")
  add_column :table_name, :column_name, :column_type, {column_options}                                                   end
                                            {column_options}                                                             def self.down
                                                                                                                          Customer.delete_all
 :null          true or false      if false, the underlying column has a not null constraint                             end
                                  added by the database engine                                                          end
 :limit         integer           set a limit on the size of the field
 :default       string            set a default value for the column
 :precision     integer           Specifies the precision for a :decimal column.
                                                                                                         ‹execute
                                                                                                                                   Miscellaneous methods
 :scale         integer           Specifies the scale for a :decimal column.
                                                                                                         Takes a single string identifying a valid SQL command to execute directly.
‹change_column                                                                                             execute "alter table line_items add constraint fk_line_item_prod-
Change the data type of the specified column                                                             ucts foreign key (product_id) references products(id)"
  change_column :table_name, :column_name, :new_column_type                                              ‹IrreversibleMigration
‹rename_column                                                                                           Use in the down method of a migration file to raise an exception when the up methods
Renames the specified column.                                                                            of the same migration file can not be reversed, e.g. changing a column type from :in-
                                                                                                         teger to :string.
  rename_column :table_name, :old_column_name, :new_column_name                                            raise ActiveRecord::IrreversibleMigration
‹remove_column
Removes the specified column.
  remove_column :table_name, :column_name
                                                                                                        ‹add_index
                                                                                                                                               Indexes
                                                                                                        Creates an index for the specified column.
                                     script/generate                                                       add_index :table_name, :column_name, :unique => true
                                                                                                        ‹remove_index
 script/generate migration new_migration_filename field_name:column_
 type name:string age:integer date_of_birth:date                                                        Remove an index ffrom the specified column.
                                                                                                           remove_index :table_name, :column_name

                                      Rake tasks                                                     db:schema:dump                Create a db/schema.rb file that can be portably used against
                                                                                                                                   any database supported by ActiveRecord
 db:create             Creates a single database specified in config/databases.yml                   db:schema:load                Load a schema.rb file into the database
 db:create:all         for the current RAILS_ENV or creates all the databases                        db:sessions:create            Create a sessions table for use with CGI::Sessions::Activ
 db:drop               Drops a single database specified in config/databases.yml                                                   eRecordStore
 db:drop:all           for the current RAILS_ENV or drops all the databases                          db:sessions:clear             Clear the sessions table
 db:fixtures:load      Load fixtures from test/fixtures into the current environ-                    db:structure:dump             Dump database structure to SQL file
                       ment's database
 db:migrate            Run all unapplied migrations                                                  db:reset                      Drops the database, creates the database and then runs migra-
                                                                                                                                   tions against the database. Takes a VERSION argument as well
 db:migrate:up         Move forward to the next migration, or back to the previous                                                 as RAILS_ENV
 db:migrate:down       migration                                                                     db:rollback STEP=4            Takes a STEP argument to determine how many version to
 db:migrate VERSION=18 Migrate database to specific version                                                                        rollback, the default being one version
 db:migrate RAILS_     Use migrations to recreate tables in the testing or production                db:test:prepare               Clone your database structure into the test database
 ENV=production        databases                                                                     db:version                    Tells you the current version your database is at


 www.dizzy.co.uk/cheatsheets                                                                                                                                                    This work is licensed under the Creative
                                                                                                                                                                                Commons Attribution-NonCommercial-
                                                                                                                                                                                NoDerivs 2.0 License. To view a copy
                                                                                                                                                                                of this license, visit http://creativecom-
                                                                                                                                                                                mons.org/licenses/by-nc-nd/2.0/uk

More Related Content

What's hot

What's hot (20)

Where's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord MigrationsWhere's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord Migrations
 
03 structures
03 structures03 structures
03 structures
 
DataFrame in Python Pandas
DataFrame in Python PandasDataFrame in Python Pandas
DataFrame in Python Pandas
 
Move Into Drupal Using The Migrate Module
Move Into Drupal Using The Migrate ModuleMove Into Drupal Using The Migrate Module
Move Into Drupal Using The Migrate Module
 
Python
PythonPython
Python
 
Pandas Series
Pandas SeriesPandas Series
Pandas Series
 
Nn
NnNn
Nn
 
List and Dictionary in python
List and Dictionary in pythonList and Dictionary in python
List and Dictionary in python
 
DBIx-DataModel v2.0 in detail
DBIx-DataModel v2.0 in detail DBIx-DataModel v2.0 in detail
DBIx-DataModel v2.0 in detail
 
Advanced geoprocessing with Python
Advanced geoprocessing with PythonAdvanced geoprocessing with Python
Advanced geoprocessing with Python
 
SVGo: a Go Library for SVG generation
SVGo: a Go Library for SVG generationSVGo: a Go Library for SVG generation
SVGo: a Go Library for SVG generation
 
Stata Programming Cheat Sheet
Stata Programming Cheat SheetStata Programming Cheat Sheet
Stata Programming Cheat Sheet
 
Data Management in R
Data Management in RData Management in R
Data Management in R
 
Array &strings
Array &stringsArray &strings
Array &strings
 
Data Visualization 2020_21
Data Visualization 2020_21Data Visualization 2020_21
Data Visualization 2020_21
 
Pandas csv
Pandas csvPandas csv
Pandas csv
 
dbms lab manual
dbms lab manualdbms lab manual
dbms lab manual
 
Stata cheatsheet transformation
Stata cheatsheet transformationStata cheatsheet transformation
Stata cheatsheet transformation
 
Database concepts
Database conceptsDatabase concepts
Database concepts
 
Stata cheat sheet: data transformation
Stata  cheat sheet: data transformationStata  cheat sheet: data transformation
Stata cheat sheet: data transformation
 

Similar to rails-migrations_1

05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptx05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptx
MohamedNowfeek1
 
Vectors Intro.ppt
Vectors Intro.pptVectors Intro.ppt
Vectors Intro.ppt
puneet680917
 

Similar to rails-migrations_1 (20)

Performing Data Science with HBase
Performing Data Science with HBasePerforming Data Science with HBase
Performing Data Science with HBase
 
MatlabIntro (1).ppt
MatlabIntro (1).pptMatlabIntro (1).ppt
MatlabIntro (1).ppt
 
Introduction to Cassandra
Introduction to CassandraIntroduction to Cassandra
Introduction to Cassandra
 
Introduction to sql
Introduction to sqlIntroduction to sql
Introduction to sql
 
Database
Database Database
Database
 
C++ process new
C++ process newC++ process new
C++ process new
 
Data import-cheatsheet
Data import-cheatsheetData import-cheatsheet
Data import-cheatsheet
 
Mito, a successor of Integral
Mito, a successor of IntegralMito, a successor of Integral
Mito, a successor of Integral
 
S.M.A.R.T. Biml - Standardize, Model, Automate, Reuse and Transform (SQLSatur...
S.M.A.R.T. Biml - Standardize, Model, Automate, Reuse and Transform (SQLSatur...S.M.A.R.T. Biml - Standardize, Model, Automate, Reuse and Transform (SQLSatur...
S.M.A.R.T. Biml - Standardize, Model, Automate, Reuse and Transform (SQLSatur...
 
Rails DB migrations
Rails DB migrationsRails DB migrations
Rails DB migrations
 
Lecture 9.pptx
Lecture 9.pptxLecture 9.pptx
Lecture 9.pptx
 
Data Wrangling with dplyr and tidyr Cheat Sheet
Data Wrangling with dplyr and tidyr Cheat SheetData Wrangling with dplyr and tidyr Cheat Sheet
Data Wrangling with dplyr and tidyr Cheat Sheet
 
05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptx05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptx
 
Les09
Les09Les09
Les09
 
Class 12 computer sample paper with answers
Class 12 computer sample paper with answersClass 12 computer sample paper with answers
Class 12 computer sample paper with answers
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Vectors Intro.ppt
Vectors Intro.pptVectors Intro.ppt
Vectors Intro.ppt
 
R training3
R training3R training3
R training3
 
Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)
 
Amir Salihefendic: Redis - the hacker's database
Amir Salihefendic: Redis - the hacker's databaseAmir Salihefendic: Redis - the hacker's database
Amir Salihefendic: Redis - the hacker's database
 

More from brecke

jQuery-Visual-Cheat-Sheet-1.4.2
jQuery-Visual-Cheat-Sheet-1.4.2jQuery-Visual-Cheat-Sheet-1.4.2
jQuery-Visual-Cheat-Sheet-1.4.2
brecke
 
jQuery Visual Cheat Sheet (by WOORK)_1
jQuery Visual Cheat Sheet (by WOORK)_1jQuery Visual Cheat Sheet (by WOORK)_1
jQuery Visual Cheat Sheet (by WOORK)_1
brecke
 
javascript-cheat-sheet-v1_1
javascript-cheat-sheet-v1_1javascript-cheat-sheet-v1_1
javascript-cheat-sheet-v1_1
brecke
 
git-cheat-sheet
git-cheat-sheetgit-cheat-sheet
git-cheat-sheet
brecke
 
Rails_3_Cheat_Sheets
Rails_3_Cheat_SheetsRails_3_Cheat_Sheets
Rails_3_Cheat_Sheets
brecke
 
JSP Syntax_1
JSP Syntax_1JSP Syntax_1
JSP Syntax_1
brecke
 
jQuery1.2.cheatsheet.v1.0_1
jQuery1.2.cheatsheet.v1.0_1jQuery1.2.cheatsheet.v1.0_1
jQuery1.2.cheatsheet.v1.0_1
brecke
 
jQuery-Visual-Cheat-Sheet-1.4.2
jQuery-Visual-Cheat-Sheet-1.4.2jQuery-Visual-Cheat-Sheet-1.4.2
jQuery-Visual-Cheat-Sheet-1.4.2
brecke
 
jQuery Visual Cheat Sheet (by WOORK)_1
jQuery Visual Cheat Sheet (by WOORK)_1jQuery Visual Cheat Sheet (by WOORK)_1
jQuery Visual Cheat Sheet (by WOORK)_1
brecke
 
javascript-cheat-sheet-v1_1
javascript-cheat-sheet-v1_1javascript-cheat-sheet-v1_1
javascript-cheat-sheet-v1_1
brecke
 
git-cheat-sheet
git-cheat-sheetgit-cheat-sheet
git-cheat-sheet
brecke
 

More from brecke (11)

jQuery-Visual-Cheat-Sheet-1.4.2
jQuery-Visual-Cheat-Sheet-1.4.2jQuery-Visual-Cheat-Sheet-1.4.2
jQuery-Visual-Cheat-Sheet-1.4.2
 
jQuery Visual Cheat Sheet (by WOORK)_1
jQuery Visual Cheat Sheet (by WOORK)_1jQuery Visual Cheat Sheet (by WOORK)_1
jQuery Visual Cheat Sheet (by WOORK)_1
 
javascript-cheat-sheet-v1_1
javascript-cheat-sheet-v1_1javascript-cheat-sheet-v1_1
javascript-cheat-sheet-v1_1
 
git-cheat-sheet
git-cheat-sheetgit-cheat-sheet
git-cheat-sheet
 
Rails_3_Cheat_Sheets
Rails_3_Cheat_SheetsRails_3_Cheat_Sheets
Rails_3_Cheat_Sheets
 
JSP Syntax_1
JSP Syntax_1JSP Syntax_1
JSP Syntax_1
 
jQuery1.2.cheatsheet.v1.0_1
jQuery1.2.cheatsheet.v1.0_1jQuery1.2.cheatsheet.v1.0_1
jQuery1.2.cheatsheet.v1.0_1
 
jQuery-Visual-Cheat-Sheet-1.4.2
jQuery-Visual-Cheat-Sheet-1.4.2jQuery-Visual-Cheat-Sheet-1.4.2
jQuery-Visual-Cheat-Sheet-1.4.2
 
jQuery Visual Cheat Sheet (by WOORK)_1
jQuery Visual Cheat Sheet (by WOORK)_1jQuery Visual Cheat Sheet (by WOORK)_1
jQuery Visual Cheat Sheet (by WOORK)_1
 
javascript-cheat-sheet-v1_1
javascript-cheat-sheet-v1_1javascript-cheat-sheet-v1_1
javascript-cheat-sheet-v1_1
 
git-cheat-sheet
git-cheat-sheetgit-cheat-sheet
git-cheat-sheet
 

Recently uploaded

Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 

Recently uploaded (20)

Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAK
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at Comcast
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
Top 10 Symfony Development Companies 2024
Top 10 Symfony Development Companies 2024Top 10 Symfony Development Companies 2024
Top 10 Symfony Development Companies 2024
 
Strategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsStrategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering Teams
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
THE BEST IPTV in GERMANY for 2024: IPTVreel
THE BEST IPTV in  GERMANY for 2024: IPTVreelTHE BEST IPTV in  GERMANY for 2024: IPTVreel
THE BEST IPTV in GERMANY for 2024: IPTVreel
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 

rails-migrations_1

  • 1. Cheatsheet • Migrations Column Types1 Shortcut methods² ‹db2 ‹mysql ‹openbase ‹Oracle ‹postgresql ‹sqlite ‹sqlserver ‹Sybase t.column t.change t.rename :binary blob(32768) blob object blob bytea blob image image t.remove t.change_default t.references :boolean decimal(1) tinyint(1) boolean number(1) boolean boolean bit bit t.remove_ref- t.belongs_to t.remove_be- :date date date date date date date datetime datetime erences longs_to :datetime timestamp datetime datetime date timestamp datetime datetime datetime t.timestamps t.index t.remove_index :decimal decimal decimal decimal decimal decimal decimal decimal decimal float float float number float float float(8) float(8) :float :integer int int(11) integer number(38) integer integer int int directory structure :string varchar(255) varchar(255) char(4096) varchar2(255) * varchar(255) varchar(255) varchar(255) db :text clob(32768) text text clob text text text text time datetime datetime time schema.rb :time time time time date :timestamp timestamp datetime timestamp date timestamp datetime datetime timestamp migrate 20080812205401_create_products.rb Table methods 20080812215015_add_data.rb ‹change_table Provides a block that enables you to alter columns on an existing table using various shortcut methods² example_migration.rb change_table :table_name, {options} do |t| class CreateCustomers < ActiveRecord::Migration t.change :column_name, :new_column_type def self.up t.remove :column_name create_table :customers, :primary_key => :customer_id, :options => end "auto_increment = 10000" do |t| ‹create_table t.integer :customer_id t.string :name, :limit => 30, :null => false Creates a table on the database. Creates a table called :table_name and makes the table t.integer :age object available to a block that can then add columns to it by specifying column_types1 or t.boolean :premium, :default => 0 utilising shortcut methods² such as using belongs_to to specify foreign keys. t.binary :photo, :limit => 2.megabytes create_table :table_name, {table_options} do |t| t.timestamps t.string :name, {column_options} t.text :notes, :default => "No notes recorded" end end add_column :customers, :surname, :string, :limit => 50 {table_options} add_column :orders, :price, :decimal, :precision => 8, :force true or false if true, forces drop of an existing table of the same name :scale => 2 before creation the new one Customer.create :name => "David", :surname => "Smith", :age => "32", :premium => "1", :notes => "One of our top customers!" :temporary true or false if true, creates a temporary table, one that goes away when end the application disconnects from the database def self.down :id true or false if false, defines a table with no primary key, for example drop_table :customers when you need to define a join table end :primary_key :symbol overrides the default name of :id for the primary column. end Use this to specify the name of the column in the database that Rails will use to store the primary key :options "string" pass raw options to your underlying database, e.g. auto_in- Fixtures crement = 10000. Note that passing options will cause you to lose the default ENGINE=InnoDB statement Fixtures contain data which can be loaded into your database using migrations. For example, to load data into a table named customers... ‹drop_table 1. Create a directory, db/migrate/data Destroys the specified table. 2. Create a file, customers.yml, inside db/migrate/data drop_table :table_name 3. Generate a new migration file: ruby script/generate migration load_cus- tomers_data ‹rename_table 4. Edit it to load data from the customers.yml file into your customers table Renames the specified table. ‹customers.yml ‹migration.rb rename_table :old_table_name, :new_table_name melissa: require 'active_record/fixtures' name: Melissa class LoadCustomerData Column methods age: 18 def self.up down ‹add_column david: directory = File.join(File.dirname(__FILE__), name: David "data") Creates a new column on the specified table. age: 23 Fixtures.create_fixtures(directory, "customers") add_column :table_name, :column_name, :column_type, {column_options} end {column_options} def self.down Customer.delete_all :null true or false if false, the underlying column has a not null constraint end added by the database engine end :limit integer set a limit on the size of the field :default string set a default value for the column :precision integer Specifies the precision for a :decimal column. ‹execute Miscellaneous methods :scale integer Specifies the scale for a :decimal column. Takes a single string identifying a valid SQL command to execute directly. ‹change_column execute "alter table line_items add constraint fk_line_item_prod- Change the data type of the specified column ucts foreign key (product_id) references products(id)" change_column :table_name, :column_name, :new_column_type ‹IrreversibleMigration ‹rename_column Use in the down method of a migration file to raise an exception when the up methods Renames the specified column. of the same migration file can not be reversed, e.g. changing a column type from :in- teger to :string. rename_column :table_name, :old_column_name, :new_column_name raise ActiveRecord::IrreversibleMigration ‹remove_column Removes the specified column. remove_column :table_name, :column_name ‹add_index Indexes Creates an index for the specified column. script/generate add_index :table_name, :column_name, :unique => true ‹remove_index script/generate migration new_migration_filename field_name:column_ type name:string age:integer date_of_birth:date Remove an index ffrom the specified column. remove_index :table_name, :column_name Rake tasks db:schema:dump Create a db/schema.rb file that can be portably used against any database supported by ActiveRecord db:create Creates a single database specified in config/databases.yml db:schema:load Load a schema.rb file into the database db:create:all for the current RAILS_ENV or creates all the databases db:sessions:create Create a sessions table for use with CGI::Sessions::Activ db:drop Drops a single database specified in config/databases.yml eRecordStore db:drop:all for the current RAILS_ENV or drops all the databases db:sessions:clear Clear the sessions table db:fixtures:load Load fixtures from test/fixtures into the current environ- db:structure:dump Dump database structure to SQL file ment's database db:migrate Run all unapplied migrations db:reset Drops the database, creates the database and then runs migra- tions against the database. Takes a VERSION argument as well db:migrate:up Move forward to the next migration, or back to the previous as RAILS_ENV db:migrate:down migration db:rollback STEP=4 Takes a STEP argument to determine how many version to db:migrate VERSION=18 Migrate database to specific version rollback, the default being one version db:migrate RAILS_ Use migrations to recreate tables in the testing or production db:test:prepare Clone your database structure into the test database ENV=production databases db:version Tells you the current version your database is at www.dizzy.co.uk/cheatsheets This work is licensed under the Creative Commons Attribution-NonCommercial- NoDerivs 2.0 License. To view a copy of this license, visit http://creativecom- mons.org/licenses/by-nc-nd/2.0/uk