Pundit policy_scope error: undefined method `admin?' for nil:NilClass

后端 未结 2 410
长情又很酷
长情又很酷 2020-12-21 11:45

Running into something I don\'t understand with Pundit,

Using Rails 4.2.5.1, Pundit 1.1.0 with Devise for authentication.

I\'m trying to use a policy scope f

相关标签:
2条回答
  • 2020-12-21 12:01

    This happens because there is no user when you are not logged in. (Probably to user variable nil value is assigned somewhere, so you are trying to call admin? method on nil object)

    If you use ruby 2.3.0 or newer you had better use safe navigation

      if user&.admin?
        scope.order('id DESC')
      else
        scope.where('published: true')
      end
    

    If you user other ruby version

    if user.try(:admin?)
      scope.order(id: :desc)
    else
      scope.where(published: true)
    end
    
    0 讨论(0)
  • 2020-12-21 12:14

    You can use try:

    if user.try(:admin?)
      # do something
    end
    

    http://api.rubyonrails.org/v4.2.5/classes/Object.html#method-i-try

    0 讨论(0)
提交回复
热议问题