有趣的问题。为了我自己的参考,让我尝试在这个问题的上下文中总结Rails Recipe书中提出的解决方案。
1) 首先在database.yml
中添加
permissions:
adapter: mysql
database: permissions
username: root
password:
socket: /tmp/mysql.sock
2) 制作权限模型调用外部数据库
class Permission < ActiveRecord::Base
establish_connection :permissions
end
3) 创建(迁移)一个 Permission Reference 表 与 Permission Id 列
4) 使用 PermissionReference 模型作为到 Permission 模型的链接
class PermissionReference < ActiveRecord::Base
belongs_to :permission
has_and_belongs_to_many :companies,
:join_table => 'companies_permissions',
:foreign_key => 'permission_id'
end
5) 最后将 Company 与 Permission 关联
class Company < ActiveRecord::Base
has_and_belongs_to_many :permissions,
:class_name => 'PermissionReference',
:join_table => 'companies_permissions',
:association_foreign_key => 'permission_id'
end
您可能想考虑通过子类化调用外部数据库的模型进行重构
class External < ActiveRecord::Base
self.abstract_class = true
establish_connection :permissions
end
class Permission < External
end