2014-11-02 2 views
0

그래서 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 

내가 :memberGuest 모두,이 일을 시도하지만, 나에게 내 Post#Index 페이지에 무한 리디렉션 순환 준 - 내 root_path입니다 :

can :read, Post.published 

여기에서 Post.publishedpublication_status = "published" 인 모든 게시물의 배열을 반환합니다.

이 내가 선언하는 방법입니다 내 Post.rb에 :

enum publication_status: [ :unpublished, :published ] 

어떻게 이것을 달성합니까?

답변

0

나는 이것을 알아 냈다. 매력처럼 작동

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 

: 내 Post#Show에서

, 나는 단순히 이런 짓을.

누군가가 더 우아한 방법을 가지고 있다면, ability.rb 안에 내가 알고 싶습니다.

블록을 사용하여 많은 순열을 시도하고 ability.rb의 모든 재즈를 시도했지만 아무 것도 효과가 없었습니다.

cancancan 이미 리소스가 loads_and_authorize이기 때문에 컨트롤러에 기본으로 추가 된 set_post 메서드를 제거해야했습니다.

0

당신이 Post 모델 publication_status라는 이름의 열이있는

#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 

다음이가 주어 작동 시도

관련 문제