LoginSignup
0
2

More than 5 years have passed since last update.

【ActiveRecord】非RailsのActiveRecordでMigrationする

Last updated at Posted at 2017-11-12

非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

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2