开发者

Scoped roles using mongoid

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.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜