【发布时间】:2013-08-13 11:44:39
【问题描述】:
我正在 Rails 中构建一个多租户 Web 应用程序,需要为我的一些模型对象提供特定于租户的标签。
这是一个虚构的例子来描述我的意思:
我有一个角色模型对象,每个租户应该有不同的标签。
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
validates_presence_of :name
end
在摄影租户中,我需要将可用角色名称列为:
- 版主
- 专家
- 学徒
- 查看者
在 Journalism 租户中,我需要将可用的角色名称列为:
- 编辑器
- 副主编
- 记者
- 读者
本质上,应用程序中始终存在四个级别的权限,但在不同的租户中,每个角色只是具有不同的名称。所以在上面的例子中,摄影Moderator和新闻Editor拥有相同的权限,只是标签不同。
我可以使用has_many :through 关联,但我宁愿避免为了获得角色标签而必须加入三个表。
class Tenant < ActiveRecord::Base
has_many :roles, :through => :tenant_roles
end
class TenantRole < ActiveRecord::Base
belongs_to :tenant
belongs_to :role
validates_presence_of :name
end
class Role < ActiveRecord::Base
has_many :tenants, :through => :tenant_roles
end
我还考虑过将角色标签存储在 Redis 中(由于其他原因,我已经有了它)并使用 current_tenant.id 和 role.id 作为键。这应该很快,但这是个坏主意吗?
class Role < ActiveRecord::Base
@tenant_roles = Redis::Set.new('tenant_roles')
def name(current_tenant)
@tenant_roles["#{current_tenant.id}-#{self.id}"]
end
end
关于最佳方式的任何其他想法?使用has_many :though 是最好的方法吗?
谢谢!
【问题讨论】:
-
您可以使用 i18n 翻译。另外:这并不是大多数人在使用该术语时所指的真正意义上的多租户。
-
谢谢 Mike - 我曾经想过使用 i18n 翻译,但它似乎有点错误,因为它不是严格意义上的翻译。你能给我一些建议吗?
-
Ps - 我正在使用 Postgres,以防万一。
-
如何判断观看的人是“摄影”还是“新闻”?
-
他们将被注册为不同租户的用户。现在我使用子域来确定当前租户。
标签: ruby-on-rails activerecord model label multi-tenant