rails/rails — Issue #3498: issues when 'joins' accros multiple database's model
Author: jmaniv
Created: 2011-11-03 06:07:14+00:00
State: open

unfortunately I have an issue when come across multiple database.

My environment: Ruby 1.9.2p290, Rails 3.0.9 and RubyGem 1.8.8

The situation is this: I have two model connect with two different database on same host and also establishing association between each other.
database connection specifying in each model, look likes

class Patient < ActiveRecord::Base
self.establish_connection "main"
has_many :visits
end

class Visit < ActiveRecord::Base
self.establish_connection "lab"
belongs_to :patient
end

This much seems to be working:
> Patient.connection.instance_eval { @config[:database] }
=> "main"
> Visit.connection.instance_eval { @config[:database] }
=> "lab"

I can successfully query in Visit and User model separately that fetches records from appropriate database
> Visit.where(:status => "NEW")
=> [ ... results .. ]
> Patient.where(:name => "yy%")
=> [ ... results .. ]

I got an error when I try to use joins:
@visits = Visit.joins(:patient)
Errors: Mysql2::Error: Table 'lab.patients' doesn't exist: SELECT visits.* FROM visits INNER JOIN patients ON patients.id IS NULL

Here 'patients' table is in 'main' database and 'visits' table in 'lab' database.
I doubt when executing the code, that Rails is considering 'patients' table is part of 'lab' database [which holds 'visits' table].

After research in site, I tried adding following in active record model:

set_table_name 'sub.visits'
def self.table_name_prefix
"sub."
end
end

but it raise exceptions:
NoMethodError: undefined method `eq' for nil:NilClass

It seems to me that Rails3 doesn't actually support multiple database.