411 REFERENCE · Wikibooks
Ruby on Rails/ActiveRecord/Migrations/SQL
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
The migration system have a lot of helpers you can use to do the stuff you want to do. Sometimes you need to do stuff that's not covered by these helpers, though. That's where the execute helper comes in.
The execute helper
The execute helper is a method for use in migrations that takes one attribute - a SQL command, as a string, and will execute the SQL just like any other migration. It will also break the migration process (like the migration helpers do) if the SQL server returned an error when executing the command.
Usefull queries
Add a default value to a column
def self.up
execute "ALTER TABLE items ALTER parent_id SET DEFAULT 0"
end
def self.down
execute "ALTER TABLE items ALTER parent_id DROP DEFAULT"
end
Add a primary key
def self.up
execute "ALTER TABLE taggings ADD id int(11) DEFAULT NULL auto_increment PRIMARY KEY"
end
def self.down
remove_column :taggings, :id
end