I am trying to setup a has_many :through relationship between two models
User and CustomerAccount through another join model AccountOwnership
(the underlying tables which BELONG to two DIFFERENT DATABASES).
Here is the relevant code
class User < ActiveRecord::Base
has_many :account_ownerships, :dependent => :destroy
has_many :companies, :through => :account_ownerships
end
class AccountOwnership < ActiveRecord::Base
belongs_to :user
belongs_to :company, :class_name => “Reporting::CustomerAccount”
end
class CustomerAccount < Reporting::Base
set_table_name “customers”
establish_connection(“db2_#{RAILS_ENV}”)
end
a = AccountOwnership.new(:user_id => 2, :company_id => 10)
a.user ## Returns the correct user
a.company ## returns the correct CustomerAccount instance
also
a.user.account_ownership ## returns a as anticipated
but
a.user.companies ## produces the following error:
#ActiveRecord::StatementInvalid: Mysql::Error: Table
#‘db2.account_ownerships’ doesn’t exist: SELECT customers
.* FROM
#customers
INNER JOIN account_ownerships
ON customers
.id =
#account_ownerships
.company_id WHERE ((account_ownerships
.user_id
= 4))
The issue here is that account_ownerships, users tables are contained in
one default database (say db1), and the customers table is contained in
a different database (say db2). The connections to the databases are
configured properly, but during the lookup since there is only one
connection object available, Rails tries to find the account_ownerships
database in db2 and hence fails.
It looks like my design/logic might be flawed because I cannot see a way
to connect to two different databases using the same connection, but I
would be thrilled to see if there is a workaround, without changing the
design. (I am reluctant to change the design because db2 is not under my
control)
Please suggest any alternate mechanisms to setup this association in
Rails.
Thanks in advance.
M