Matic Jurglič
Matic Jurglič

Reputation: 861

How to dynamically set schema_format for custom db rake tasks in Rails?

I'm running a Rails 4.2.5 app with two different databases. The first one, let's call it db_main, uses sql schema format (because this DB has some DB constructs that ruby schema can't handle). I achieved this by putting config.active_record.schema_format = :sql in application.rb.

Now, there is a second DB, let's call it db_other. This DB has a ruby schema, but the problem is that its db tasks expect an sql schema. I defined all db related tasks for this database like so:

namespace :other do
  task :set_custom_db_config_paths do
    ENV['SCHEMA'] = 'db_other/schema.rb'
    Rails.application.config.paths['db'] = ['other']
    Rails.application.config.paths['db/migrate'] = ['db_other/migrate']
    Rails.application.config.paths['config/database'] = ['config/database_other.yml']
 end

 namespace :db do
   task :migrate => :set_custom_db_config_paths do
   Rake::Task["db:migrate"].invoke
 end

 ... other tasks

 namespace :test do
  task :prepare => :set_custom_db_config_paths do
    # Tried setting ActiveRecord::Base.schema_format = :ruby here, but problem remains
      Rake::Task["db:test:prepare"].invoke
     end
   end
  end
end

When calling rake other:test:prepare, the following happens

`psql:db_other/schema.rb:135: ERROR: syntax error at or near "#"``

How can I configure so that rake other:test:prepare will take the ruby schema, and not the SQL one?

Upvotes: 5

Views: 566

Answers (1)

Tamer Shlash
Tamer Shlash

Reputation: 9523

Try this:

  task :set_custom_db_config_paths do
    ENV['SCHEMA'] = 'db_other/schema.rb'
    Rails.application.config.paths['db'] = ['other']
    Rails.application.config.paths['db/migrate'] = ['db_other/migrate']
    Rails.application.config.paths['config/database'] = ['config/database_other.yml']
    Rails.application.config.active_record.schema_format = :ruby
  end

Note the last line setting Rails.application.config.active_record.schema_format = :ruby

Upvotes: 2

Related Questions