Niels Kristian
Niels Kristian

Reputation: 8865

Rails share custom database connection between classes - without class inheritance?

I have a replica database slave running, where I want to send some readonly calls to, to offload the master. For this reason I would like to create two customs models, that connect separately to that database, so that I can use those, whenever I have the need to offload some queries.

I have two classes:

class Car < ActiveRecord::Base
  has_many :prices
end

class Price < ActiveRecord::Base
  belongs_to :car
end

Rails has the possibility to share custom database connections on model level like this:

class MyCustomDbConnection < ActiveRecord::Base
  self.abstract_class = true
  establish_connection({database: 'www.slavedb.com', port: 5432, pass: 'some'})
end

class ReadonlyCar < MyCustomDbConnection
end

class ReadonlyPrice < MyCustomDbConnection
end

While this works well, my use case is that I would ALSO like to have the ´ReadonlyCar´ and ReadonlyPrice inherit from the original models that uses the default ActiveRecord::Base.connection. This is needed to have the ReadonlyCar behave exactly like the original one Car (business logic). Now I can't do class inheritance from both ReadonlyCar < MyCustomDbConnection and ReadonlyCar < Carat the same time, so how do I get the full functionality from Car, but share the same connection to the slave between both ReadonlyCar and ReadonlyPrice?

Upvotes: 1

Views: 300

Answers (1)

kaikuchn
kaikuchn

Reputation: 795

You could write a module where in the included hook you do that call to establish the connection.

module MyCustomDbConnection
  def self.included(base)
    base.establish_connection(
      database: 'www.slavedb.com',
      port: 5432,
      pass: 'some'
    )
  end
end

class ReadOnlyCar < Car
  include MyCustomDbConnection
end

Upvotes: 2

Related Questions