Search code examples
ruby-on-railsdevisepundit

Rails 4 with Devise & Pundit - @user or @current_user


I am trying to make an app with Rails 4 and devise and pundit (with rolify for roles)

In the:

class ApplicationPolicy
  attr_reader :user, :record

  def initialize(user, record)
    @user = user
    @record = record
  end

According to this Go Rails video: https://gorails.com/episodes/authorization-with-pundit?autoplay=1

This attr_reader section in the application policy covers all of the rest of the policies - so you don't need to repeat in each one.

However, my current question is given that I use devise, should I change the application policy to use current_user instead of user? Eg:

class ApplicationPolicy
      attr_reader :current_user, :record

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

None of the examples I've found do it this way, but I don't understand why not.

I was hoping to figure out if I'm off the the right start before I start writing rules for each policy. Does every controller action that i make a policy for need to refer to user or should I change all of them to current_user?


Solution

  • You can use whatever you want to do the authorization logic.

    Pundit will send in current_user from your controller when you call something like authorize @object.

    From in your class you will just have to do your logic with current_user instead of user.

    Why would you want to change it? From your applications perspective, you are really authorizing a user to do something, not necessarily a current_user. So keeping it as user follows conventions