0

我有具有多对多关联的模型,例如通过 RoleAssignment 连接的用户和角色

DB1 中的表:

users
role_assignments

DB2 中的表:

roles

我可以使用 访问 DB1 中的用户role_one.users,但无法使用 访问 DB2 中的角色user_one.roles。它给出了一个例外

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 知道 role_assignments 驻留在 DB1 中而不是 DB2 中?谢谢

4

2 回答 2

1

Solved my problem using table_name_prefix as shown at http://emphaticsolutions.com/2009/11/23/has_many_through_across_databases.html

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

then

class Role< ExternalActiveRecord
  ...
end

and

class User < ActiveRecord::Base
  ...
end
于 2012-05-18T06:55:08.550 回答
0

我自己没有做过,但是您可以将 activerecord 子类化以维护多个数据库连接。请参阅此博客文章:

http://www.messaliberty.com/2009/02/ruby-how-to-use-multiple-databases-with-activerecord/

于 2012-05-17T11:42:13.190 回答