Ruby on Rails/ActiveRecord/Migrations/SQL

From Wikibooks, open books for an open world
< Ruby on Rails‎ | ActiveRecord‎ | Migrations
Jump to navigation Jump to search

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[edit]

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[edit]

Add a default value to a column[edit]

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[edit]

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