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

孤者浪人 提交于 2019-11-29 16:17:59

You can use try:

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

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!