1

I am using pundit gem to authorize in my system app. before to implement pundit I had my endpoint index like this:

    def index
        @cars = Car.all
        render json: @cars
    end

worked ok, but now with pundit, i made a change like this

    def index
        @cars = Car.all
        authorize @cars
    end

Now I am getting this error:

current_user must be defined before the impersonates method

mtsyumm
  • 39
  • 5

1 Answers1

0

Pundit works a little differently for the index route. typically you want to do exactly what you where trying authorize @post but we only pass one record.

So for you:

# posts_controller.rb
def index
  @posts = policy_scope(Post)
end

this hits the following in pundit:

# app/policies/post_policy.rb
# [...]
class Scope < Scope
  def resolve
    scope.all # If users can see all posts
    # scope.where(user: user) # If users can only see their posts
    # scope.where("name LIKE 't%'") # If users can only see posts starting with `t`
    # ...
  end
end

As for your error related to the current_user, is that coming from pundit? In pundit itself your current_user (from devise for example) will be just user, such that you can check record.user == user.

Haumer
  • 460
  • 4
  • 15