使用 mongoid 限定角色范围

发布于 2024-10-12 13:52:01 字数 228 浏览 3 评论 0原文

使用 Mongoid,如果我有一个帐户模型并希望将具有特定角色的用户分配给该帐户,那么最好将关系嵌入到帐户、用户中,还是创建一个角色集合将帐户映射到具有角色名称的用户?

我希望能够返回帐户的所有用户,并使用 Cancan 之类的工具验证当前用户是否有权访问该帐户。

构建帐户的推荐方式是什么<->基于用户角色的关系?一个用户可能属于多个可能具有不同角色的帐户,类似于 Basecamp 的工作方式。

Using Mongoid, if I have an Account model and want to assign Users with specific roles to that account, is it best to embed the relationship within the Account, User or create a roles collection mapping account to user with the role name?

I want to be able to return all users of an account as well as validate that the current user has access to the account with something like Cancan.

What is the recommended way to structure an Account <-> User role based relationship? A user could belong to multiple accounts potentially with different roles, similar to how Basecamp works.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撩发小公举 2024-10-19 13:52:01

我最近正是实现了这一点。虽然稍微复杂一点。

我所做的是将角色嵌入到用户中,

class User
  include Mongoid::Document
  embeds_many :roles
end

class Role
  include Mongoid::Document

  field :kind, :type => Symbol
  field :account_id, :type => BSON::ObjectId
  embedded_in :users, :inverse_of => :roles
end

class Account
  include Mongoid::Document
end

#adding a role to user
account = Account.create
user = User.create
user.roles.create(:kind => :admin, :account_id => account.id)

#all users of an account
User.where("roles.account_id" => account.id)

#users accounts
Account.where(:_id => user.roles.map(&:account_id))

#in cancan ability
can :access, Account, :_id => user.roles.map(&:account_id)

我还让 cancan 查询可访问_by 工作,但它需要 mongoid 的一些 mods 才能使其工作。

希望有帮助
(注意:我刚刚在这里编写了这段代码,所以不确定它是否运行)

I have recently implemented exactly this. Although a bit more complicated.

What I did was embed the roles in the user

class User
  include Mongoid::Document
  embeds_many :roles
end

class Role
  include Mongoid::Document

  field :kind, :type => Symbol
  field :account_id, :type => BSON::ObjectId
  embedded_in :users, :inverse_of => :roles
end

class Account
  include Mongoid::Document
end

#adding a role to user
account = Account.create
user = User.create
user.roles.create(:kind => :admin, :account_id => account.id)

#all users of an account
User.where("roles.account_id" => account.id)

#users accounts
Account.where(:_id => user.roles.map(&:account_id))

#in cancan ability
can :access, Account, :_id => user.roles.map(&:account_id)

I also had the cancan query accessible_by working but it required some mods to mongoid to get it to work.

Hope that helps
(Note: I just wrote this code in here so not sure if it runs)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文