Help us understand the problem. What is going on with this article?

railsで任意の環境のdbをrails dbコマンドで作成・削除する。

More than 3 years have passed since last update.

例えば以下の様に、ブログアプリと管理アプリが別々にDBを持つ場合等。

config/database.yml
default: &default
  adapter: mysql2
  encoding: utf8mb4
  pool: 5
  username: root
  password:

development:
  <<: *default
  database: blog_development

admin_development:
  <<: *default
  database: blog_admin_development

rake db:create を追加で実装することによって、デフォルトのコマンド実行と追加で別のDBの作成を行うことができる。

lib/tasks/db/create.rake
def create(configuration)
  begin
    ActiveRecord::Tasks::MySQLDatabaseTasks.new(configuration).create
    puts "Created database '#{configuration['database']}'"
  rescue ActiveRecord::Tasks::DatabaseAlreadyExists
    puts "Database '#{configuration['database']}' already exists"
  rescue => error
    puts error
    puts "Couldn't create database for #{configuration.inspect}"
    raise
  end
end

namespace :db do
  task :create do
    configurations = ActiveRecord::Base.configurations.dup
    rails_env = ENV['RAILS_ENV'].presence || ENV['RACK_ENV'].presence

    if rails_env
      create configurations["admin_#{rails_env}"]
    else
      %w(development test).each do |env|
        create configurations["admin_#{env}"]
      end
    end
  end
end

dropコマンドも同様に作成できる。

postgresqlやsqlite3をお使いの方は以下を参考に。

参考: https://github.com/rails/rails/tree/master/activerecord/lib/active_record/tasks

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away