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

时间:2011-04-07 15:08:29

标签: ruby-on-rails ruby-on-rails-3 authorization 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

任何想法在这里出了什么问题?

2 个答案:

答案 0 :(得分:5)

控制器的authorize! :destroy, @photo操作应为destroy

答案 1 :(得分:1)

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

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

因为它已经由CanCan完成。