2011-08-30 49 views
3

Cancan在用戶登錄時工作正常。但是當用戶是「訪客」時,我希望他們能夠看到一些照片,但不是那些照片的父郵件有一個限制employees_only標誌設置。Cancan不會加載嵌套的資源,因爲我期望它

問題是如果在@photos陣列中有任何與employee_only帖子相關的照片,則Cancan將丟棄CanCan::AccessDenied in PhotosController#index。但是控制器中不應該有load_and_authorize_resource :photo, :through => :event已經從@photos中刪除了那些未經授權的記錄?

ability.rb

class Ability 
    include CanCan::Ability 

    def initialize(user) 
    user ||= User.new # guest user (not logged in) 

    if user.role? :admin 
     can :manage, :all 
    elsif user.role? :moderator 
     can :read, :all 
     can :manage, Post 
     can :manage, Event 
    elsif user.role? :employee 
     can :read, :all 
     can :create, Post 
     can :update, Post, :user_id => user.id 
     can :destroy, Post, :user_id => user.id 
     can :update, User, :id => user.id 
     can :create, Photo 
     can :update, Photo, :id => user.id 
     can :destroy, Photo, :id => user.id 
    else 
     can :read, :all 
     cannot :read, Post, :employee_only => true 
     cannot :read, Photo, :post => { :employee_only => true } ## <- problem? 
    end 
    end 
end 

event.rb:

class Event < ActiveRecord::Base 
Event has_many :posts 
Event has_many :photos, :through => :posts 

post.rb

class Post < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :event 
    has_many :photos, :dependent => :destroy 

photos_controller:

class PhotosController < ApplicationController 
    load_and_authorize_resource :event      ## <- problem? 
    load_and_authorize_resource :photo, :through => :event ## <- problem? 

    def index 
    # @event = Event.find(params[:event_id]) 
    # @photos = @event.photos.all 

    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render json: @events } 
    end 
    end 
    ... 

user.rb#不知道這是要解決此問題,但JIC:

class User < ActiveRecord::Base 
    attr_protected :roles_mask 
    has_many :posts 
    has_many :photos, :through => :posts 
    ... 
+1

** Cancan **失寵並且我沒有收到備忘錄? – Meltemi

回答

0

首先,在你的能力文件中刪除

cannot :read, Photo, :post => { :employee_only => true } ## <- problem? 

我不認爲你需要,當你被限制在帖子上。

然後在你的控制器改變

load_and_authorize_resource :event      ## <- problem? 
load_and_authorize_resource :photo, :through => :event ## <- problem? 

load_and_authorize_resource :post 
load_and_authorize_resource :photo, :through => :post 

我相信你正在嘗試做的是通過與後因職位僅限於那些employee_only加載照片= false,你隱式限制照片。然後,在您的照片控制器中,您需要加載帖子,以便它可以用來加載和授權照片。在cancan(我認爲)中應該發生的是內部連接是在posts.employee_only = false的帖子和照片之間完成的。