0

I'm trying to migrate to Pundit and having a bit of trouble.

I have a user model and a photo model.

User has many photos and photo is a nested resource of user. In my controller I do

@user = User.find(params[:user_id])
@photos = @user.photos

In my cancan ability class I have

can :create, Photo, :user => { :id => user.id }

and in a view I would use

<% if can? :create, @user => Photo %>

anyone know how to correctly do this with Pundit?

Thank you in advance

keither78
  • 11
  • 2
  • Only way I could get it to pass so far was adding a add_photo to the UserPolicy with record == user and in view doing `<% if policy(@user).add_photo? %>` – keither78 Aug 19 '14 at 08:34

1 Answers1

0

Pundit approaches authorization differently than CanCan by providing authorization of objects. For starters, you'll want to write a PhotoPolicy:

class PhotoPolicy
  attr_reader :user, :photo

  def create?
    photo.user.id == user.id # Use photo.user_id if you have that column available 
  end    
end

Then in your view you can do:

<% if policy(@photo).create? %>

Notice that I'm calling this on a single Photo. If you want a policy for getting all the photos the user has access you would want to use a scope. Let me know if this is the case and I'll update my answer.

Saul
  • 911
  • 1
  • 8
  • 19
  • Saul thanks for the answer and it makes sense. Guess my main question would be. If you have say /:company/tasks/:task_id how would you make sure the user has permission on the company and task? For nested resources. I am probably over thinking it. Thanks again. – keither78 Aug 27 '14 at 19:39
  • Writing polices really comes down to thinking through who can access what in your website. In the case of your companies/tasks question, it would depend. If a user belongs to a company, can they access all that company's tasks? Or only their own tasks for that company? The best way to get started if you're stuck is to write out a list of things user have access to and then start writing the policies from that list. – Saul Aug 27 '14 at 19:43