非RailsでActiveRecordを使ってMigrationするためのメモ。
Migrationファイルの作成
任意のディレクトリ下(db/migrate
など)にMigrationファイルを作成していきます。
- ファイル名とクラス名を揃える
- バージョン管理用のprefixをつける
- バージョンによってMigration Versioningの指定を行う に注意してファイルを追加する。
db/migrate/001_create_projects.rb
class CreateProjects < ActiveRecord::Migration[5.1]
def self.up
create_table :projects do |t|
t.string :name
end
end
def self.down
drop_table :projects
end
end
Migrationを実行する
Rakefileなりから以下を呼び出す。
migrate
メソッドの引数に Migrationファイルが格納されたディレクトリのパスを渡す。
require 'active_record'
ActiveRecord::Base.establish_connection(
adapter: "postgresql",
host: "localhost",
username: "XXXXX",
password: "YYYYY",
database: "my_db",
)
ActiveRecord::Migrator.migrate('./db/migrate')
参考
非Rails AppでActiveRecord::Migrationを使う + Rakeでバージョン管理する - Qiita
ActiveRecordのMigrationを単体で使う - 黒縁眼鏡は海を飛ぶ
Rails Migration versioningと5.1での変更点 - chulip.org
rails じゃなくても ActiveRecord を使う - momota.txt