【问题标题】:Rails 4 - Granular permissions schemaRails 4 - 粒度权限架构
【发布时间】:2014-02-10 04:27:11
【问题描述】:
我目前正在构建一个 Rails 应用程序,并坚持决定如何实现权限架构。我有一个用户模型和一个项目模型。每个用户可以创建一个或多个项目。同时用户可以是其他项目的管理员或访客。我希望用户只能看到他们创建或受邀参与的项目。
我听说过 CanCan gem,但还不知道如何在我的情况下使用它。谁能建议如何做到这一点?提前致谢!
【问题讨论】:
标签:
ruby-on-rails
permissions
ruby-on-rails-4
cancan
roles
【解决方案1】:
如果您是 Rails 新手,在转向像 devise + cancan 这样的现成解决方案之前,尝试自己实现类似 auth 总是好的。话虽如此,推出自己的基于角色的身份验证可能是一个相当大的挑战。
在这个特定示例中,您可以做的是使用“多对多直通”关系将您的用户连接到您的项目,从而使您的关系本身具有像常规模型一样的属性。 http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
在您的示例中,您可以执行以下操作:
class User < ActiveRecord::Base
has_many :appointments
has_many :projects, through: :roles
end
class Role < ActiveRecord::Base
# role might now have attributes like :admin, moderator
# or could specify individual permissions like :canread, :canwrite, :candelete
# which you could check before allowing changes to projects.
belongs_to :user
belongs_to :project
end
class Project < ActiveRecord::Base
has_many :roles
has_many :users, through: :roles
end