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

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 MigrationsEleanor McHugh
 
DataFrame in Python Pandas
DataFrame in Python PandasDataFrame in Python Pandas
DataFrame in Python PandasSangita Panchal
 
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 Modulenyccamp
 
List and Dictionary in python
List and Dictionary in pythonList and Dictionary in python
List and Dictionary in pythonSangita Panchal
 
DBIx-DataModel v2.0 in detail
DBIx-DataModel v2.0 in detail DBIx-DataModel v2.0 in detail
DBIx-DataModel v2.0 in detail Laurent Dami
 
Advanced geoprocessing with Python
Advanced geoprocessing with PythonAdvanced geoprocessing with Python
Advanced geoprocessing with PythonChad Cooper
 
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 generationAnthony Starks
 
Stata Programming Cheat Sheet
Stata Programming Cheat SheetStata Programming Cheat Sheet
Stata Programming Cheat SheetLaura Hughes
 
Data Visualization 2020_21
Data Visualization 2020_21Data Visualization 2020_21
Data Visualization 2020_21Sangita Panchal
 
Stata cheatsheet transformation
Stata cheatsheet transformationStata cheatsheet transformation
Stata cheatsheet transformationLaura Hughes
 
Stata cheat sheet: data transformation
Stata  cheat sheet: data transformationStata  cheat sheet: data transformation
Stata cheat sheet: data transformationTim Essam
 

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

Performing Data Science with HBase
Performing Data Science with HBasePerforming Data Science with HBase
Performing Data Science with HBaseWibiData
 
Introduction to Cassandra
Introduction to CassandraIntroduction to Cassandra
Introduction to CassandraHanborq Inc.
 
C++ process new
C++ process newC++ process new
C++ process new敬倫 林
 
Mito, a successor of Integral
Mito, a successor of IntegralMito, a successor of Integral
Mito, a successor of Integralfukamachi
 
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...Cathrine Wilhelmsen
 
Rails DB migrations
Rails DB migrationsRails DB migrations
Rails DB migrationsDenys Kurets
 
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 SheetDr. Volkan OBAN
 
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.pptxMohamedNowfeek1
 
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 answersdebarghyamukherjee60
 
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)Achmad Solichin
 
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 databaseit-people
 

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.2brecke
 
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)_1brecke
 
javascript-cheat-sheet-v1_1
javascript-cheat-sheet-v1_1javascript-cheat-sheet-v1_1
javascript-cheat-sheet-v1_1brecke
 
git-cheat-sheet
git-cheat-sheetgit-cheat-sheet
git-cheat-sheetbrecke
 
Rails_3_Cheat_Sheets
Rails_3_Cheat_SheetsRails_3_Cheat_Sheets
Rails_3_Cheat_Sheetsbrecke
 
JSP Syntax_1
JSP Syntax_1JSP Syntax_1
JSP Syntax_1brecke
 
jQuery1.2.cheatsheet.v1.0_1
jQuery1.2.cheatsheet.v1.0_1jQuery1.2.cheatsheet.v1.0_1
jQuery1.2.cheatsheet.v1.0_1brecke
 
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.2brecke
 
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)_1brecke
 
javascript-cheat-sheet-v1_1
javascript-cheat-sheet-v1_1javascript-cheat-sheet-v1_1
javascript-cheat-sheet-v1_1brecke
 
git-cheat-sheet
git-cheat-sheetgit-cheat-sheet
git-cheat-sheetbrecke
 

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

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 

Recently uploaded (20)

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

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