目次

2009年1月23日金曜日

補足:チュートリアル(1) もう一回フィールドを作り直したい場合

前回のblogが大変長くなりましたので、マイグレーション関係の補足。
一度、migrateしてしまうと、簡単にはやりなおせません。
方法は3つ
1,DBを一から作り直す
2,バージョンを増やしてマイグレーションスクリプトを作り直した後、マイグレーションを行う。
3,initializing.rakeという初期化用ファイルを使う

1,の場合
mysqlでデータベースを削除(drop データベース名;)した後、もう一度データベースを作り、マイグレーションし直す。めんどくさい(笑)

2,の場合
002_テーブル名.rbと名前をつけてマイグレーションするというもの。しかし、rails2.0以降、この仕様は変更されたので、上手くいくか不明。未確認です、ごめんなさい(苦笑)

3,の場合
これも本にのっていたスクリプトを使ってちょいっとやっちゃいます。1,を自動でやってくれるrakeタスクです。一番簡単ですが、これをするとフィクスチャファイル以外の、これまで蓄積されたデータがパァになってしまうので注意。
lib>taskフォルダの下に以下のソースを「initializing.rake」という名前で保存しましょう。


namespace :db do
desc "Create the development and test databases."
task :create do
require 'yaml'

path = File.dirname(__FILE__) + "/../../config/database.yml"
configurations = YAML.load_file(path)

%w(development test).each do |env|
config = configurations[env]
if config['adapter'] == 'mysql'
command = sprintf(%{mysql --user %s}, config['username'])
command += " --password=#{config['password']}" if config['password'] and !config['password'].empty?
command += " --host #{config['host']}" if config['host'] and !config['host'].empty?
command += " --port #{config['port']}" if config['port'] and !config['port'].empty?
sh command + %( --execute="drop database if exists #{config['database']}")
if config['encoding'] and !config['encoding'].empty?
sh command + %( --execute="create database #{config['database']} default character set #{config['encoding']}")
else
sh command + %( --execute="create database #{config['database']}")
end
elsif config['adapter'] == 'postgresql'
# 未実装
else
raise "Unsupported database adapter #{config['adapter']}"
end
end
end

desc "Create and initialize the development and test databases."
task :initialize => ["db:create", "db:migrate", "db:import:development", "db:test:prepare"]
end




ファイルを準備した後は、
rake db:initialize
これでOK!

0 件のコメント: