3

My Rails 3.2 app use two different databases. The main os is a MySQL while the oher is a sqlserver DB :

development:
    adapter: mysql2
    encoding: utf8
    database: mydb
    username: myuser
    password: ***
secondbase:
    adapter: sqlserver
    database: anotherbase
    username: anotheruser
    password: ***

I have two associated models :

class Account < ActiveRecord::Base
    establish_connection :secondbase
    has_many :docs
end

class Docs < ActiveRecord::Base
    belongs_to :account
end

Since the two model use table on two differents database, I suppose I can't use eager_loading and load associated data with join or includes

But I think preload should still allow me to load the data using two queries (instead of N + 1)

However, when trying to use preloadin my controller, it raises an error :

Docs.where(someconditions).preload(:account)

returns

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'USE [anotherbase]

What could I do to preload the Account data and avoid N + 1 queries when dusplaying the Docs with some Account details in my views ?

tshepang
  • 12,111
  • 21
  • 91
  • 136
LapinLove404
  • 1,939
  • 1
  • 21
  • 26
  • Um ... well, this is kind of not necessarily something Rails is designed to do. Of course it's possible, but chances are in order to use the magic of AR, you'll want to make it look like there's a single database once you get to Rails. Check to see if there are gems out there that are designed to do this. Here's an older thread on SO with some good links: http://stackoverflow.com/questions/1825844/multiple-databases-in-rails – Tom Harrison Mar 19 '12 at 02:10
  • I am aware that Rails is not designed to handle multiple database. Using `establish_connection` when required in my Models is good enough for most of my needs. I'd just like to improve performances using eager/pre-loading. – LapinLove404 Mar 21 '12 at 09:51

1 Answers1

0

Have you looked at Apartment gem: https://github.com/bradrobertson/apartment ?

It provides you the means to deal with multiple databases.

Paulo Fidalgo
  • 21,709
  • 7
  • 99
  • 115