当用户登录时,Cancan 工作正常。但是当用户是“客人”时,我希望他们能够看到一些照片,而不是那些照片的父帖子employees_only
设置了限制标志的照片。
问题是如果数组中有任何与employee_only
帖子相关的照片,@photos
那么 Cancan 会抛出CanCan::AccessDenied in PhotosController#index
. 但是load_and_authorize_resource :photo, :through => :event
控制器中不应该删除那些未经授权的记录@photos
吗?
能力.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
事件.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
照片控制器:
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
...