我有一个具有:published属性(boolean)的Post模型和一个具有role属性(string)的用户模型。有三个角色:ROLES = %w[admin publisher author]
我不希望角色是author的用户能够在帖子模型上设置或编辑:published字段。
我使用的是CanCan (和RailsAdmin gem),我的简化Ability.rb文件如下所示:
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有人有做这类事情的小贴士吗?
发布于 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在“资源属性”一节中
发布于 2012-03-03 05:34:24
查看这篇文章:How do I use CanCan with rails admin to check for ownership
它展示了如何根据用户角色使字段不可见。
更新我能够使用以下代码在rails管理中设置选项:
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’)并设置默认值。
希望这对某些人有帮助。
发布于 2012-04-28 03:34:14
在CanCan 2.0出现之前,我已经通过创建一个具有受限可访问性的模型子类解决了这个问题,类似于:
class AuthorPost < Post
attr_protected :published
end然后给作者访问AuthorPosts的权限:can :manage => AuthorPost
然后,在您的控制器中,您可以在before_filter中设置所需的资源:
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。
对于这种方法比铁路广播中描述的方法更有效还是更不有效,我持观望态度。出于我的目的,它完全保留了原始模型,所以我的其他代码不会受到影响--只是允许我给一些用户提供更少的可编辑字段。
https://stackoverflow.com/questions/5921591
复制相似问题