如何限制特定范围仅限具有特定角色的用户?
问题描述:
所以我有一个Post
模型。我的posts
可以发布或不发布。我正在使用Rolify,CanCanCan和Devise。如何限制特定范围仅限具有特定角色的用户?
我希望发生什么是我的:admin
的用户,应该能够查看所有帖子的Post#Show
动作,但我:member
或guest
用户(即非登录)应该永远只能够看到Post.published
职位。
我ability.rb
看起来是这样的:
if user.has_role? :admin
can :manage, :all
#Member
elsif user.has_role? :member
can :read, :all
can :create, Post
can :status, Post
can :update, Post do |post|
post.try(:user) == user
end
#Guest
else
can :read, :all
can :create, Post
can :status, Post
end
我试着这样做,对于:member
和Guest
,但它给了我Post#Index
页上的无限重定向循环 - 这是我root_path
:
can :read, Post.published
其中Post.published
返回publication_status = "published"
所有帖子的数组。
这是我宣布,我Post.rb
:
enum publication_status: [ :unpublished, :published ]
如何实现这一目标?
答
我想通了。
在我Post#Show
,我只是这样做:
def show
if current_user and current_user.has_role? :admin or :editor
@post = Post.find(params[:id])
else
@post = Post.published.find(params[:id])
end
end
这就像一个魅力。
如果有人有一个更优雅的方式,说我想知道ability.rb
。
我在ability.rb
中尝试了很多使用块和所有这些爵士乐的排列,但没有任何成效。
我还不得不在我的控制器中删除默认添加的set_post
方法,因为cancancan
已经是loads_and_authorize
的资源。
答
请尝试以下
#Member
elsif user.has_role? :member
can :read, Post, publication_status: :published
can :create, Post
can :status, Post
can :update, Post, user_id: user.id
# same goes for the Guest user
这将工作给您在Post
模型有一个名为publication_status
列