マイグレーション

  • rails demo
  • config/database.yml
development:
  adapter: mysql
  database: demo_development
  username: hoge
  password:
  host: localhost
  encoding: utf8
  socket: /var/run/mysqld/mysqld.sock
  • config/environment.rb
$KCODE = 'UTF8'
  • app/controllers/application.rb
class ApplicationController < ActionController::Base
  before_filter :set_charset

  private
  def set_charset
    headers["Content-Type"] = "text/html; charset=UTF-8"
  end
end
  • db/create_database.sql
drop database if exists demo_development;
create database demo_development;
grant all on demo_development.* to 'hoge'@'localhost';
exit
  • script/generate migration FooBar
  • rake migrate (VERSION=x)

外部キー制約やユニーク制約*1は今のところ手動だと思う。

class AddForeignKeyOrders < ActiveRecord::Migration
  def self.up
    add_index :orders, :product_id
    execute "ALTER TABLE orders ADD CONSTRAINT orders_product_id_fk FOREIGN KEY (product_id) REFERENCES products (id)"
  end

  def self.down
    execute "ALTER TABLE orders DROP FOREIGN KEY orders_product_id_fk"
    remove_index :orders, :product_id
  end
end
  • rake db_schema_dump
  • rake db_schema_import

schema.rbというファイルにスキーマがダンプされる。
手動でやったもの(execute)は、schema.rbに反映されない。

*1:add_index の :uniqueオプションがあった