make queries on multiple db in same action controller with transaction rails?

683 views Asked by At

I have in my database.yml :

default: &default
  [...]

development_1:
  <<: *default
  database: dev1

development_2:
  <<: *default
  database: dev2

I need to make many queries in foo action but using these 2 DB :

class UsersController < ApplicationController

   def foo
      users_nb            = User.count #this use my default db : dev1
      other_connexion     = ActiveRecord::Base.establish_connection("#{Rails.env}_2").connection
      users_nb_other_site = connexion.execute("SELECT COUNT(*) FROM users").first[0]
   end

end

that works, BUT I encapsulate all action controller in transaction like :

ActiveRecord::Base.transaction do
  begin
    yield
  rescue Exception => e
    raise ActiveRecord::Rollback
end

with this, my previous code doesn't works, it raise an error :

ActiveRecord::StatementInvalid in UsersController#foo NoMethodError: undefined method `query' for nil:NilClass Did you mean? to_query: ROLLBACK

the line of error is : ActiveRecord::Base.transaction do

So how can I do to make my connexion and queries on another db in same time that my principal db?

1

There are 1 answers

0
Matrix On

Ok, my problem was I don't understand ActiveRecord::Base.establish_connection overwrite my first connexion and the transaction too.

I create an abstract class like said here : https://makandracards.com/makandra/10169-when-connecting-to-a-second-database-take-care-not-to-overwrite-existing-connections

class ReadDatabaseConnection < ActiveRecord::Base
  def self.abstract_class?
    true # So it gets its own connection
  end
end

ReadDatabaseConnection.establish_connection(slave_settings)

I keep my 2 connexion like that, without pb !