有趣的问题。为了我自己的参考,让我尝试在这个问题的上下文中总结Rails 食谱书中提出的解决方案。
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 Id列的Permission Reference 表
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)最后将公司关联到许可
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