首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >CanCan:限制用户根据角色设置特定模型属性的能力

CanCan:限制用户根据角色设置特定模型属性的能力
EN

Stack Overflow用户
提问于 2011-05-07 22:11:13
回答 4查看 7.7K关注 0票数 20

我有一个具有:published属性(boolean)的Post模型和一个具有role属性(string)的用户模型。有三个角色:ROLES = %w[admin publisher author]

我不希望角色是author的用户能够在帖子模型上设置或编辑:published字段。

我使用的是CanCan (和RailsAdmin gem),我的简化Ability.rb文件如下所示:

代码语言:javascript
运行
复制
class Ability
  include CanCan::Ability
  def initialize(user)
    user ||= User.new

    if user.role? :admin
      can :manage, :all
    elsif user.role? :publisher
      can :manage, Post
    elsif user.role? :author
      # I want to prevent these guys from setting the :published attribute
    end

  end
end

有人有做这类事情的小贴士吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-05-07 22:20:45

到目前为止这是不可能的。但根据这一点:https://github.com/ryanb/cancan/issues/326这个特性应该在CanCan2.0中。

更新:你可以在CanCan 2.0分支上看到这个:https://github.com/ryanb/cancan/tree/2.0在“资源属性”一节中

票数 13
EN

Stack Overflow用户

发布于 2012-03-03 05:34:24

查看这篇文章:How do I use CanCan with rails admin to check for ownership

它展示了如何根据用户角色使字段不可见。

更新我能够使用以下代码在rails管理中设置选项:

代码语言:javascript
运行
复制
config.model User do
  edit do
    configure :organization do
      visible do
        bindings[:view]._current_user.max_role_name != 'admin' ? false : true
      end
    end

    configure :organization_id, :hidden do
      visible do
        true if bindings[:view]._current_user.max_role_name != 'admin'
      end
      default_value do
        bindings[:view]._current_user.organization_id if bindings[:view]._current_user.max_role_name != 'admin'
      end
    end

    include_all_fields
  end
end

如果登录的用户不是管理员,此配置将隐藏组织字段。然后,它将显示一个类型字段(设置为organization_id =‘hidden’)并设置默认值。

希望这对某些人有帮助。

票数 3
EN

Stack Overflow用户

发布于 2012-04-28 03:34:14

在CanCan 2.0出现之前,我已经通过创建一个具有受限可访问性的模型子类解决了这个问题,类似于:

代码语言:javascript
运行
复制
class AuthorPost < Post
  attr_protected :published
end

然后给作者访问AuthorPosts的权限:can :manage => AuthorPost

然后,在您的控制器中,您可以在before_filter中设置所需的资源:

代码语言:javascript
运行
复制
before_filter :set_resource
...
  private
    def set_resource
      if current_user and current_user.author?
        @resource = AuthorPost
      else
        @resource = Post
      end
      params[:post] ||= params[:author_post]
    end

最后一个警告:您将不能在该控制器中使用load_and_authorize_resource。您必须手动完成此操作,详细信息如下:https://github.com/ryanb/cancan/wiki/Controller-Authorization-Example

您需要用@resource替换Project

对于这种方法比铁路广播中描述的方法更有效还是更不有效,我持观望态度。出于我的目的,它完全保留了原始模型,所以我的其他代码不会受到影响--只是允许我给一些用户提供更少的可编辑字段。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5921591

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档