0
votes

I'm using the pundit gem and trying to figure out how to use it to prevent access to an index page that belongs to a user other than the current_user.

The examples only talk about how to scope the results to the current_user but no how to actually prevent access to the page itself if the current_user is NOT the owner of the record.

Any help appreciated

Thanks

1
I would think an index page doesn't belong to any user. Is the goal to restrict access to admins only? - moveson
@moveson It is the index page for a specific user, it's there page. Perhaps it shouldn't be an index page but a separate action in the users controller like user_posts - Robbo
That would make more sense to me. The pattern described below should work; just replace index? with user_posts?. See comment from @Fede Bonisconti below for an alternative suggestion as to where to put the authorized_to_edit? logic. If you include it anywhere other than the User model, you will need to call authorized_to_edit?(current_user) instead of current_user.authorized_to_edit? - moveson

1 Answers

1
votes

Maybe you want something like this? (For class ModelName)

# /policies/model_name_policy.rb

class ModelNamePolicy
  attr_reader :current_user, :resource

  def initialize(current_user, resource)
    @current_user = current_user
    @resource = resource
  end

  def index?
    current_user.authorized_to_edit?(resource)
  end

end

# /models/user.rb

class User < ActiveRecord::Base

  def authorized_to_edit?(resource)
    admin? | (id == resource.created_by) # Or whatever method you want to call on your model to determine ownership
  end

end

EDIT: Note that you will also need to call authorize from your controller to invoke the policy.