Switching databases in Rails/Postgres is causing error

Viewed 69

I'm trying to setup a testing environment where I can simulate writing to a master database and reading from a slave database. Currently I have a parent model with a before_save and after_save callback that switches to slave and back to master.

I'm running into this error though ActiveRecord::StatementInvalid: PG::ConnectionBad: connection is closed: ROLLBACK

application_record.rb

class ApplicationRecord < ActiveRecord::Base

  self.abstract_class = true

  before_save :switch_to_master
  after_save :switch_to_slave

  def switch_to_slave
    config = YAML.load_file(File.join(Rails.root, "config", "database.yml"))[Rails.env.to_s]
    ApplicationRecord.establish_connection(config)
  end

  def switch_to_master
    config = YAML.load_file(File.join(Rails.root, "config", "database_master.yml"))[Rails.env.to_s]
    ApplicationRecord.establish_connection(config)
  end

end

master_slave_test.rb

require 'test_helper'

class MasterSlaveTest < ActionController::TestCase

  def test_one
    @user = users(:john)

    @user.update(last_name: 'Change')
    @user.update(last_name: 'Change')


    assert "Change", @user.reload.last_name
  end

end

database.yml

test:
  adapter: postgresql
  database: autobrain_test_slave
  host: localhost

database_master.yml

test:
  adapter: postgresql
  database: autobrain_test
  host: localhost
0 Answers
Related