.preload using two databases
My Rails 3.2 application uses two different databases. The main os is MySQL and oher is sqlserver DB:
development:
adapter: mysql2
encoding: utf8
database: mydb
username: myuser
password: ***
secondbase:
adapter: sqlserver
database: anotherbase
username: anotheruser
password: ***
I have two related models:
class Account < ActiveRecord::Base
establish_connection :secondbase
has_many :docs
end
class Docs < ActiveRecord::Base
belongs_to :account
end
Since the two models are using the table in two different databases, I assume that I cannot use eager_loading and load related data using join
orincludes
But I think I preload
should still allow me to load data using two queries (instead of N + 1)
However, when trying to use preload
in my controller, it throws 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 can I do to preload account details and avoid N + 1 requests when duplicating documents with some account details in my views?
source to share
Have you looked at the gem of the apartment: https://github.com/bradrobertson/apartment ?
It provides you with the means to work with multiple databases.
source to share