Andrew
Andrew

Reputation: 43123

Rails + CanCan: User should be able to delete own photo, but cannot

So, I'm using Rails 3 with CanCan for authorization. I want all users to be able to delete photos they created, and I thought I had this set up correctly, but it isn't working...

Here's my Ability class:

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

Here's my controller action:

def destroy
  @photo = Photo.find(params[:id])

  authorize! :delete, @photo
  @photo.destroy
  redirect_to :back, :notice => 'Photo deleted.'
end

Any ideas what's going wrong here?

Upvotes: 2

Views: 2451

Answers (2)

RocketR
RocketR

Reputation: 3766

Actually, if you're using load_and_authorize_resource in your controller you can leave out the

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

as it's already done by CanCan.

Upvotes: 1

htanata
htanata

Reputation: 36944

Should be authorize! :destroy, @photo on your controller's destroy action.

Upvotes: 5

Related Questions