Ruby on rails Rails具有多对多关联的多个数据库
我有多对多关联的模型,例如用户和角色,通过角色分配进行连接 DB1中的表:Ruby on rails Rails具有多对多关联的多个数据库,ruby-on-rails,many-to-many,associations,multiple-databases,Ruby On Rails,Many To Many,Associations,Multiple Databases,我有多对多关联的模型,例如用户和角色,通过角色分配进行连接 DB1中的表: users role_assignments DB2中的表: roles 我可以使用role\u one.users访问DB1中的用户,但是我不能使用user\u one.roles访问DB2中的角色。这是一个例外 ActiveRecord::StatementInvalid: Mysql2::Error: Table 'db2_development.role_assignments' doesn't exist:
users
role_assignments
DB2中的表:
roles
我可以使用role\u one.users
访问DB1中的用户,但是我不能使用user\u one.roles
访问DB2中的角色。这是一个例外
ActiveRecord::StatementInvalid: Mysql2::Error: Table 'db2_development.role_assignments' doesn't exist:
SELECT `roles`.* FROM `roles` INNER JOIN `role_assignments` ON `roles`.`id` = `role_assignments`.`role_id`
WHERE `role_assignments`.`user_id` = 1
是否有人知道如何从用户访问角色,或者如何让rails知道角色分配驻留在DB1中而不是DB2中?thx我自己还没有做过,但是您可以将activerecord子类化以维护多个db连接。请参阅此博客帖子:
使用
表\u name\u prefix
解决了我的问题,如所示
class ActiveRecord::Base
def self.table_name_前缀
“应用程序名称开发”
结束
结束
类ExternalActiveRecord
然后
类角色
及
class用户
我已连接多个数据库。事实上,我已经解决了我的问题。现在我遇到了一个新问题,我尝试将用户n Role与Role\u alias\u分配连接起来,我无法使用alias访问角色,例如:在其他地方有很多:Role\u别名,source::Role,through::Role\u alias\u分配
。它给出了一个错误未定义的方法
角色\u别名'#`
class ActiveRecord::Base
def self.table_name_prefix
"app_name_development."
end
end
class ExternalActiveRecord < ActiveRecord::Base
self.abstract_class = true
establish_connection "external_development"
def self.table_name_prefix
"external_app_name_development."
end
end
class Role< ExternalActiveRecord
...
end
class User < ActiveRecord::Base
...
end