Nona
Nona

Reputation: 5462

Rake task create not getting Rails.env in db:create for ActiveRecord>=4.05

For ActiveRecord 3.2.18, in /lib/active_record/railties/databases.rake:

  task :load_config do
    ActiveRecord::Base.configurations = Rails.application.config.database_configuration
    ActiveRecord::Migrator.migrations_paths = Rails.application.paths['db/migrate'].to_a

    if defined?(ENGINE_PATH) && engine = Rails::Engine.find(ENGINE_PATH)
      if engine.paths['db/migrate'].existent
        ActiveRecord::Migrator.migrations_paths += engine.paths['db/migrate'].to_a
      end
    end
  end

  desc 'Create the database from DATABASE_URL or config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)'
  task :create => [:load_config, :rails_env] do
    if ENV['DATABASE_URL']
      create_database(database_url_config)
    else
      configs_for_environment.each { |config| create_database(config) }
      ActiveRecord::Base.establish_connection(configs_for_environment.first)
    end
  end

For ActiveRecord 4.0.5+, in /lib/active_record/railties/databases.rake:

  task :load_config do
    ActiveRecord::Base.configurations = ActiveRecord::Tasks::DatabaseTasks.database_configuration || {}
    ActiveRecord::Migrator.migrations_paths = ActiveRecord::Tasks::DatabaseTasks.migrations_paths
  end

  desc 'Create the database from DATABASE_URL or config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)'
  task :create => [:load_config] do
    if ENV['DATABASE_URL']
      ActiveRecord::Tasks::DatabaseTasks.create_database_url
    else
      ActiveRecord::Tasks::DatabaseTasks.create_current
    end
  end

When I call bundle exec rake db:create from a Rakefile (for a gem I'm testing), ActiveRecord 3.2.18, ActiveRecord::Base.configurations gets the information it needs from my test/config/database.yml file via Rails.application.config.database_configuration. But when calling db:create using ActiveRecord 4.0.5+, ActiveRecord::AdapterNotSpecified: database configuration does not specify adapter error. It doesn't matter whether I call it with RAILS_ENV=some_environment. How do I give ActiveRecord 4.0.5+ the database configuration it needs without monkey patching it? The ideal solution is to somehow do it my Rakefile.

Upvotes: 0

Views: 541

Answers (1)

VP.
VP.

Reputation: 5141

I had the same problem, and I "fixed" with a monkey patch:

in your Rakefile, after you imported the active_record, I did the following:

# hack to make it works with sqlite3
module Rails
    def self.root
        File.dirname(__FILE__)
    end

    def self.env
        "development"
    end
end

for sure you can do whatever you want inside your "self.env" method.

Upvotes: 0

Related Questions