我正在尝试将我的用户帐户和会话数据移动到一个单独的数据库中,以便我们最终可以在多个应用程序之间共享它。
我在网上看到很多人说用来establish_connection
告诉模型连接到不同的数据库,但我无法让它工作。
配置/数据库.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
应用程序/模型/user.rb
class User < ActiveRecord::Base
establish_connection :authentication
has_one :person
end
应用程序/模型/person.rb
class Person < ActiveRecord::Base
belongs_to :user
end
这似乎很有效:
> User.connection.instance_eval { @config[:database] }
=> "authentication"
> Person.connection.instance_eval { @config[:database] }
=> "project_name_development"
我可以单独查询User
:
> User.where(:admin => true)
=> [ ... lots of results .. ]
但是一旦我尝试使用join
它就会中断:
> 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 似乎正在使用当前数据库,而不是通过反射获得正确的数据库。
我发现了差不多两年前关于这个问题的这个非常古老的错误报告,但我几乎可以肯定它是关于旧的 ARel 语法的,我真的怀疑代码示例是否会继续工作。
这甚至可能吗?
更新:通过这样做取得了一点进展:
User.joins("INNER JOIN project_name.people ON project_name.people.user_id = authentication.users.id")
但这真的很乏味,我想加入的表之一是多态的。
我尝试添加:
set_table_name 'project_name.people'
但这又回来了
NoMethodError: undefined method `eq' for nil:NilClass
在我看来,Rails3 实际上并不支持多个模式。我错了吗?