如何限制特定范围仅限具有特定角色的用户?

问题描述:

所以我有一个Post模型。我的posts可以发布或不发布。我正在使用Rolify,CanCanCan和Devise。如何限制特定范围仅限具有特定角色的用户?

我希望发生什么是我的:admin的用户,应该能够查看所有帖子的Post#Show动作,但我:memberguest用户(即非登录)应该永远只能够看到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 

我试着这样做,对于:memberGuest,但它给了我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