Adam O'Connor
Adam O'Connor

Reputation: 2682

How can I connect to a different DB for a particular method in a class?

Due to System Admin I need to do a query within our app against the slave database vs. the production database.

I can use establish_connection at the class level but do not want to disrupt other class methods. Therefore wondering, how would I create a DB connection for this one particular class method w/o having to point all of my methods to the slave db?

Kind of how you would do it in Perl or Php.

Here's an example: http://pastie.org/private/0k8xqssjrib94sd8hhjfq

Any help appreciated.

Best, Adam O

Upvotes: 4

Views: 268

Answers (3)

Adam O'Connor
Adam O'Connor

Reputation: 2682

thanks for the solutions. I ended up going with the Sequel library. Essentially I created an initializer, 'slavedb_connect' class, and use this connection to interface the slave db when needed.

I went through many attempts and got really close. However, Sequel is a graceful solution that more so follows the 'Rails/Ruby Way'.

Thanks for the help/support. Really enjoy using this site.

Upvotes: 0

charliequinn
charliequinn

Reputation: 430

This should help you https://github.com/kovyrin/db-charmer

Upvotes: 4

moritz
moritz

Reputation: 25767

I would add a method to your model like that:

class Model
  def self.on_slave
    .. connect to slave with establish_connection ..
    yield
    .. connect to production with establish_connection
  end

For every method you need the slave for, you can then do:

def self.this_operates_on_the_slave
  on_slave do
    .. operate
  end
end

Upvotes: 1

Related Questions