Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

establish_connection doesn't seem to support joins

I'm trying to move my User account and session data into a separate database so that we can eventually share it across multiple applications.

I've seen plenty of people online saying to use establish_connection to tell a model to connect to a different db, but I am unable to get this to work.

config/database.yml

development:
  adapter: mysql2
  encoding: utf8
  reconnect: true
  pool: 5
  host: localhost
  database: project_name_development

authentication:
  adapter: mysql2
  encoding: utf8
  reconnect: true
  pool: 5
  host: localhost
  database: authentication

app/models/user.rb

class User < ActiveRecord::Base
  establish_connection :authentication
  has_one :person
end

app/models/person.rb

class Person < ActiveRecord::Base
  belongs_to :user
end

This much seems to be working:

> User.connection.instance_eval { @config[:database] }
=> "authentication"
> Person.connection.instance_eval { @config[:database] }
=> "project_name_development"

and I can query User in isolation:

> User.where(:admin => true)
=> [ ... lots of results .. ]

but as soon as I try to use join it breaks:

> User.joins(:person)
ActiveRecord::StatementInvalid: Mysql2::Error: Table 'authentication.people' doesn't exist: SELECT `users`.* FROM `users` INNER JOIN `people` ON `people`.`user_id` = `users`.`id`

ARel seems to be using the current database instead of getting the correct one through reflection.

I found this very old bug report from almost two years ago about this problem, but I am almost certain it was regarding the old ARel syntax, and I really doubt the code examples would work anymore.

Is this even possible?

Update: made a little headway by doing this:

User.joins("INNER JOIN project_name.people ON project_name.people.user_id = authentication.users.id")

but that is really tedious, and one of the tables I'd like to join is polymorphic.

I tried adding:

set_table_name 'project_name.people'

but that returns

NoMethodError: undefined method `eq' for nil:NilClass

It seems to me that Rails3 doesn't actually support multiple schemas. Am I wrong?

like image 781
Adam Lassek Avatar asked Nov 14 '22 05:11

Adam Lassek


1 Answers

Have you thought about taking it out of the app layer and just replicating certain tables only with MySQL replication?

like image 96
jschorr Avatar answered Dec 25 '22 03:12

jschorr