<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Class: ActiveRecord::Migration</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> <link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" /> <script type="text/javascript"> // <![CDATA[ function popupCode( url ) { window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400") } function toggleCode( id ) { if ( document.getElementById ) elem = document.getElementById( id ); else if ( document.all ) elem = eval( "document.all." + id ); else return false; elemStyle = elem.style; if ( elemStyle.display != "block" ) { elemStyle.display = "block" } else { elemStyle.display = "none" } return true; } // Make codeblocks hidden by default document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" ) // ]]> </script> </head> <body> <div id="classHeader"> <table class="header-table"> <tr class="top-aligned-row"> <td><strong>Class</strong></td> <td class="class-name-in-header">ActiveRecord::Migration</td> </tr> <tr class="top-aligned-row"> <td><strong>In:</strong></td> <td> <a href="../../files/lib/active_record/migration_rb.html"> lib/active_record/migration.rb </a> <br /> </td> </tr> <tr class="top-aligned-row"> <td><strong>Parent:</strong></td> <td> Object </td> </tr> </table> </div> <!-- banner header --> <div id="bodyContent"> <div id="contextContent"> <div id="description"> <p> Migrations can manage the evolution of a schema used by several physical databases. It‘s a solution to the common problem of adding a field to make a new feature work in your local database, but being unsure of how to push that change to other developers and to the production server. With migrations, you can describe the transformations in self-contained classes that can be checked into version control systems and executed against another database that might be one, two, or five versions behind. </p> <p> Example of a simple migration: </p> <pre> class AddSsl < ActiveRecord::Migration def self.up add_column :accounts, :ssl_enabled, :boolean, :default => 1 end def self.down remove_column :accounts, :ssl_enabled end end </pre> <p> This migration will add a boolean flag to the accounts table and remove it if you‘re backing out of the migration. It shows how all migrations have two class methods <tt>up</tt> and <tt>down</tt> that describes the transformations required to implement or remove the migration. These methods can consist of both the migration specific methods like add_column and remove_column, but may also contain regular Ruby code for generating data needed for the transformations. </p> <p> Example of a more complex migration that also needs to initialize data: </p> <pre> class AddSystemSettings < ActiveRecord::Migration def self.up create_table :system_settings do |t| t.string :name t.string :label t.text :value t.string :type t.integer :position end SystemSetting.create :name => "notice", :label => "Use notice?", :value => 1 end def self.down drop_table :system_settings end end </pre> <p> This migration first adds the system_settings table, then creates the very first row in it using the Active Record model that relies on the table. It also uses the more advanced create_table syntax where you can specify a complete table schema in one block call. </p> <h2>Available transformations</h2> <ul> <li><tt>create_table(name, options)</tt> Creates a table called <tt>name</tt> and makes the table object available to a block that can then add columns to it, following the same format as add_column. See example above. The options hash is for fragments like "DEFAULT CHARSET=UTF-8" that are appended to the create table definition. </li> <li><tt>drop_table(name)</tt>: Drops the table called <tt>name</tt>. </li> <li><tt>rename_table(old_name, new_name)</tt>: Renames the table called <tt>old_name</tt> to <tt>new_name</tt>. </li> <li><tt>add_column(table_name, column_name, type, options)</tt>: Adds a new column to the table called <tt>table_name</tt> named <tt>column_name</tt> specified to be one of the following types: <tt>:string</tt>, <tt>:text</tt>, <tt>:integer</tt>, <tt>:float</tt>, <tt>:decimal</tt>, <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>, <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>. A default value can be specified by passing an <tt>options</tt> hash like <tt>{ :default => 11 }</tt>. Other options include <tt>:limit</tt> and <tt>:null</tt> (e.g. <tt>{ :limit => 50, :null => false }</tt>) — see ActiveRecord::ConnectionAdapters::TableDefinition#column for details. </li> <li><tt>rename_column(table_name, column_name, new_column_name)</tt>: Renames a column but keeps the type and content. </li> <li><tt>change_column(table_name, column_name, type, options)</tt>: Changes the column to a different type using the same parameters as add_column. </li> <li><tt>remove_column(table_name, column_name)</tt>: Removes the column named <tt>column_name</tt> from the table called <tt>table_name</tt>. </li> <li><tt>add_index(table_name, column_names, options)</tt>: Adds a new index with the name of the column. Other options include <tt>:name</tt> and <tt>:unique</tt> (e.g. <tt>{ :name => "users_name_index", :unique => true }</tt>). </li> <li><tt>remove_index(table_name, index_name)</tt>: Removes the index specified by <tt>index_name</tt>. </li> </ul> <h2>Irreversible transformations</h2> <p> Some transformations are destructive in a manner that cannot be reversed. Migrations of that kind should raise an <tt>ActiveRecord::IrreversibleMigration</tt> exception in their <tt>down</tt> method. </p> <h2>Running migrations from within Rails</h2> <p> The Rails package has several tools to help create and apply migrations. </p> <p> To generate a new migration, you can use </p> <pre> script/generate migration MyNewMigration </pre> <p> where MyNewMigration is the name of your migration. The generator will create an empty migration file <tt>nnn_my_new_migration.rb</tt> in the <tt>db/migrate/</tt> directory where <tt>nnn</tt> is the next largest migration number. </p> <p> You may then edit the <tt>self.up</tt> and <tt>self.down</tt> methods of MyNewMigration. </p> <p> There is a special syntactic shortcut to generate migrations that add fields to a table. </p> <pre> script/generate migration add_fieldname_to_tablename fieldname:string </pre> <p> This will generate the file <tt>nnn_add_fieldname_to_tablename</tt>, which will look like this: </p> <pre> class AddFieldnameToTablename < ActiveRecord::Migration def self.up add_column :tablenames, :fieldname, :string end def self.down remove_column :tablenames, :fieldname end end </pre> <p> To run migrations against the currently configured database, use <tt>rake db:<a href="Migration.html#M000446">migrate</a></tt>. This will update the database by running all of the pending migrations, creating the <tt>schema_migrations</tt> table (see "About the schema_migrations table" section below) if missing. It will also invoke the db:schema:dump task, which will update your db/schema.rb file to match the structure of your database. </p> <p> To roll the database back to a previous migration version, use <tt>rake db:<a href="Migration.html#M000446">migrate</a> VERSION=X</tt> where <tt>X</tt> is the version to which you wish to downgrade. If any of the migrations throw an <tt>ActiveRecord::IrreversibleMigration</tt> exception, that step will fail and you‘ll have some manual work to do. </p> <h2>Database support</h2> <p> Migrations are currently supported in MySQL, PostgreSQL, SQLite, SQL Server, Sybase, and Oracle (all supported databases except DB2). </p> <h2>More examples</h2> <p> Not all migrations change the schema. Some just fix the data: </p> <pre> class RemoveEmptyTags < ActiveRecord::Migration def self.up Tag.find(:all).each { |tag| tag.destroy if tag.pages.empty? } end def self.down # not much we can do to restore deleted data raise ActiveRecord::IrreversibleMigration, "Can't recover the deleted tags" end end </pre> <p> Others remove columns when they <a href="Migration.html#M000446">migrate</a> up instead of down: </p> <pre> class RemoveUnnecessaryItemAttributes < ActiveRecord::Migration def self.up remove_column :items, :incomplete_items_count remove_column :items, :completed_items_count end def self.down add_column :items, :incomplete_items_count add_column :items, :completed_items_count end end </pre> <p> And sometimes you need to do something in SQL not abstracted directly by migrations: </p> <pre> class MakeJoinUnique < ActiveRecord::Migration def self.up execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)" end def self.down execute "ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`" end end </pre> <h2>Using a model after changing its table</h2> <p> Sometimes you‘ll want to add a column in a migration and populate it immediately after. In that case, you‘ll need to make a call to <a href="Base.html#M000493">Base#reset_column_information</a> in order to ensure that the model has the latest column data from after the new column was added. Example: </p> <pre> 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 </pre> <h2>Controlling verbosity</h2> <p> By default, migrations will describe the actions they are taking, writing them to the console as they happen, along with benchmarks describing how long each step took. </p> <p> You can quiet them down by setting ActiveRecord::Migration.verbose = false. </p> <p> You can also insert your own messages and benchmarks by using the <tt><a href="Migration.html#M000450">say_with_time</a></tt> method: </p> <pre> def self.up ... say_with_time "Updating salaries..." do Person.find(:all).each do |p| p.update_attribute :salary, SalaryCalculator.compute(p) end end ... end </pre> <p> The phrase "Updating salaries…" would then be printed, along with the benchmark for the block when the block completes. </p> <h2>About the schema_migrations table</h2> <p> Rails versions 2.0 and prior used to create a table called <tt>schema_info</tt> when using migrations. This table contained the version of the schema as of the last applied migration. </p> <p> Starting with Rails 2.1, the <tt>schema_info</tt> table is (automatically) replaced by the <tt>schema_migrations</tt> table, which contains the version numbers of all the migrations applied. </p> <p> As a result, it is now possible to add migration files that are numbered lower than the current schema version: when migrating up, those never-applied "interleaved" migrations will be automatically applied, and when migrating down, never-applied "interleaved" migrations will be skipped. </p> <h2>Timestamped Migrations</h2> <p> By default, Rails generates migrations that look like: </p> <pre> 20080717013526_your_migration_name.rb </pre> <p> The prefix is a generation timestamp (in UTC). </p> <p> If you‘d prefer to use numeric prefixes, you can turn timestamped migrations off by setting: </p> <pre> config.active_record.timestamped_migrations = false </pre> <p> In environment.rb. </p> </div> </div> <div id="method-list"> <h3 class="section-bar">Methods</h3> <div class="name-list"> <a href="#M000448">announce</a> <a href="#M000452">connection</a> <a href="#M000453">method_missing</a> <a href="#M000446">migrate</a> <a href="#M000449">say</a> <a href="#M000450">say_with_time</a> <a href="#M000451">suppress_messages</a> <a href="#M000447">write</a> </div> </div> </div> <!-- if includes --> <div id="section"> <!-- if method_list --> <div id="methods"> <h3 class="section-bar">Public Class methods</h3> <div id="method-M000448" class="method-detail"> <a name="M000448"></a> <div class="method-heading"> <a href="Migration.src/M000448.html" target="Code" class="method-signature" onclick="popupCode('Migration.src/M000448.html');return false;"> <span class="method-name">announce</span><span class="method-args">(message)</span> </a> </div> <div class="method-description"> </div> </div> <div id="method-M000452" class="method-detail"> <a name="M000452"></a> <div class="method-heading"> <a href="Migration.src/M000452.html" target="Code" class="method-signature" onclick="popupCode('Migration.src/M000452.html');return false;"> <span class="method-name">connection</span><span class="method-args">()</span> </a> </div> <div class="method-description"> </div> </div> <div id="method-M000453" class="method-detail"> <a name="M000453"></a> <div class="method-heading"> <a href="Migration.src/M000453.html" target="Code" class="method-signature" onclick="popupCode('Migration.src/M000453.html');return false;"> <span class="method-name">method_missing</span><span class="method-args">(method, *arguments, &block)</span> </a> </div> <div class="method-description"> </div> </div> <div id="method-M000446" class="method-detail"> <a name="M000446"></a> <div class="method-heading"> <a href="Migration.src/M000446.html" target="Code" class="method-signature" onclick="popupCode('Migration.src/M000446.html');return false;"> <span class="method-name">migrate</span><span class="method-args">(direction)</span> </a> </div> <div class="method-description"> <p> Execute this migration in the named direction </p> </div> </div> <div id="method-M000449" class="method-detail"> <a name="M000449"></a> <div class="method-heading"> <a href="Migration.src/M000449.html" target="Code" class="method-signature" onclick="popupCode('Migration.src/M000449.html');return false;"> <span class="method-name">say</span><span class="method-args">(message, subitem=false)</span> </a> </div> <div class="method-description"> </div> </div> <div id="method-M000450" class="method-detail"> <a name="M000450"></a> <div class="method-heading"> <a href="Migration.src/M000450.html" target="Code" class="method-signature" onclick="popupCode('Migration.src/M000450.html');return false;"> <span class="method-name">say_with_time</span><span class="method-args">(message) {|| ...}</span> </a> </div> <div class="method-description"> </div> </div> <div id="method-M000451" class="method-detail"> <a name="M000451"></a> <div class="method-heading"> <a href="Migration.src/M000451.html" target="Code" class="method-signature" onclick="popupCode('Migration.src/M000451.html');return false;"> <span class="method-name">suppress_messages</span><span class="method-args">() {|| ...}</span> </a> </div> <div class="method-description"> </div> </div> <div id="method-M000447" class="method-detail"> <a name="M000447"></a> <div class="method-heading"> <a href="Migration.src/M000447.html" target="Code" class="method-signature" onclick="popupCode('Migration.src/M000447.html');return false;"> <span class="method-name">write</span><span class="method-args">(text="")</span> </a> </div> <div class="method-description"> </div> </div> </div> </div> <div id="validator-badges"> <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p> </div> </body> </html>