active_recordをrails以外で使う

ググるとActive Recordを単独で使う方法が出てきますが、手元のRails7系のActive Recordだと動かなかったので、調べながらやってみました。

結論

以下で動きました。

# Rakefile
require "bundler/gem_tasks"
require "bundler/setup"

require "active_record"
require "erb"

include ActiveRecord::Tasks # rubocop:disable Style/MixinUsage

root_dir = File.dirname(__FILE__)
database_config_path = File.join(root_dir, "config/database.yml")
database_config = YAML.safe_load(ERB.new(File.read(database_config_path)).result, aliases: true)

DatabaseTasks.database_configuration = database_config
DatabaseTasks.db_dir = "db"
DatabaseTasks.env = "development"
DatabaseTasks.migrations_paths = "db/migrate"
DatabaseTasks.root = root_dir

task :environment do
  ActiveRecord::Base.configurations = database_config
  ActiveRecord::Base.establish_connection :development
end

load "active_record/railties/databases.rake"

補足

ActiveRecord::Tasks::DatabaseTasks

ActiveRecord::Tasks::DatabaseTasks
migrateに関するロジックがカプセル化してまとめられているとのこと。

Example usage of DatabaseTasks outside Rails could look as such:

include ActiveRecord::Tasks
DatabaseTasks.database_configuration = YAML.load_file('my_database_config.yml')
DatabaseTasks.db_dir = 'db'
# other settings...

DatabaseTasks.create_current('production')

other settingsのところは、リンク先にそれぞれ記載されています。

active_record/railties/databases.rake

rails/databases.rake at v7.0.4.3 · rails/rails
これをloadすることでrails同様にActive Recordが利用できるようになります。便利。

$ bundle exec rake -T db
rake db:create              # Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:create:all to create all data...
rake db:drop                # Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases ...
rake db:encryption:init     # Generate a set of keys for configuring Active Record encryption in a given environment
rake db:environment:set     # Set the environment value for the database
rake db:fixtures:load       # Loads fixtures into the current environment's database
rake db:migrate             # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)
rake db:migrate:down        # Runs the "down" for a given migration VERSION
rake db:migrate:redo        # Rolls back the database one migration and re-migrates up (options: STEP=x, VERSION=x)
rake db:migrate:status      # Display status of migrations
rake db:migrate:up          # Runs the "up" for a given migration VERSION
rake db:prepare             # Runs setup if database does not exist, or runs migrations if it does
rake db:reset               # Drops and recreates all databases from their schema for the current environment and loads the seeds
rake db:rollback            # Rolls the schema back to the previous version (specify steps w/ STEP=n)
rake db:schema:cache:clear  # Clears a db/schema_cache.yml file
rake db:schema:cache:dump   # Creates a db/schema_cache.yml file
rake db:schema:dump         # Creates a database schema file (either db/schema.rb or db/structure.sql, depending on `ENV['SCHEMA_FORMAT']` or `config.activ...
rake db:schema:load         # Loads a database schema file (either db/schema.rb or db/structure.sql, depending on `ENV['SCHEMA_FORMAT']` or `config.active_...
rake db:seed                # Loads the seed data from db/seeds.rb
rake db:seed:replant        # Truncates tables of each database for current environment and loads the seeds
rake db:setup               # Creates all databases, loads all schemas, and initializes with the seed data (use db:reset to also drop all databases first)
rake db:version             # Retrieves the current schema version number