Open a mysql DB connection in a rake task

I have a Rails 3.2 application that uses PostgreSQL to store all information.

But in one Rake task, I need to establish a connection to the MySQL server. I tried to do this:

ActiveRecord::Base.establish_connection(
    :adapter  => "mysql2",
    :database => "foo",
    :user => "root", 
    :password => "",
)

      

But it just replaces my default PostgreSQL connection with this temporary MySQL.

How do I make an additional connection for an instance?

+3


source to share


2 answers


I found a very simple solution: for vanilla mysql2 gem ( https://github.com/brianmario/mysql2 )

Now my code looks like this:



client = Mysql2::Client.new(:host => "localhost", :username => "root", :database => "foobar", :password => "")
users = client.query("SELECT * FROM users")

      

After that, I have an array of results.

+5


source


Don't set it to ActiveRecord :: Base.

connection_connection connects to the database from a class as you discovered, so when you do it on AR: Base, every subclass of that (for whit, the entire database) has a connection established on it, replacing the current one.



Basically, you create a class for each of the tables you want to connect to and call the connection establishment method on them. If you want to do this in multiple tables, create a module with it and include it.

class MyCustomClass < ActiveRecord::Base
  establish_connection(
   :adapter  => "mysql2",
   :database => "foo",
   :user => "root", 
   :password => "",
  )
end

MyCustomClass.find(1)

      

+2


source







All Articles