Rails + CanCan:用户应该能够删除自己的照片,但不能



所以,我使用Rails 3与CanCan进行授权。我希望所有用户都能删除他们创建的照片,我以为我设置正确了,但是它不工作…

这是我的能力类:

class Ability
  include CanCan::Ability
  def initialize(user)
    # ONLY REGISTERED USERS CAN DO THESE THINGS
    unless user.nil?
      # ALL REGISTERED USERS CAN DO THESE THINGS
      can :read, [Photo, Context, Focus, LandUse, Vote, Rating, Comment, Profile, Article]
      can :show, Page
      # MEMBERS
      if user.has_role? :member
        can [:create, :read], Photo
        can [:update, :destroy], Photo, :user_id => user.id
        can :create, [Vote, Rating, Comment, Profile]
        can :update, [Vote, Rating, Comment, Profile], :user_id => user.id
        can [:show, :update], User do |u|
          u == user
        end
      end
      # CURATORS
      ...
      # ADMINS
      ...
    end
    # ALL VISITORS CAN DO THESE THINGS
    can :create, [User, Profile]
    can :request_invite, User
    # can :show, Page
  end
end

这是我的控制器动作:

def destroy
  @photo = Photo.find(params[:id])
  authorize! :delete, @photo
  @photo.destroy
  redirect_to :back, :notice => 'Photo deleted.'
end

你知道这里出了什么问题吗?

控制器的destroy动作应该是authorize! :destroy, @photo

实际上,如果你在控制器中使用load_and_authorize_resource你可以省略

@photo = Photo.find(params[:id])
authorize! :destroy, @photo

就像CanCan已经做的那样

相关内容

  • 没有找到相关文章

最新更新