Dmytro Vasin
Dmytro Vasin

Reputation: 823

Rails cancan gem

Hi i need help with new ( for me ) gem 'cancan'

i have a next problem: in my app i have 'Post' model and 'Photo' model ( routes: )

  resources :posts do
    resources :photos
  end

and in ability.rb i write:

class Ability
  include CanCan::Ability

  def initialize(user)

    user ||= User.new

    if user.roles.first.nil?
        can :read, Post
    #not logged
    elsif user.roles.first.name == "user"
        #loged in as user
        can :read, Post
        can :create, Post
        can :update, Post, :user_id => user.id
        can :destroy, Post , :user_id => user.id 

    elsif user.roles.first.name == "admin"
        # login as admin
        can :manage, Post
    end

  end
end

and i dont know how put thats logic: if post created by another user, current user does not have access to page

localhost:3000/post/97/photos

and he(current user) can't create there anything or destroy, in other words he can only read localhost:3000/post/97/

But if current user is autor - he have access to localhost:3000/post/97/photos, localhost:3000/post/97/photos/new and localhost:3000/post/97/photo/244/show ...

in ability something like that: can :destroy, Photo , @photo.post.user_id => user.id // but how to define @photo ?? or if you know an easier way ?

Upvotes: 0

Views: 264

Answers (1)

Flo
Flo

Reputation: 540

You can use a block like:

can :manage , Post  do | post |
  post.user_id == user.id
end

which means that only if the current user created the Post it is able to manage it.

Upvotes: 1

Related Questions