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
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
You can use try:
if user.try(:admin?)
# do something
end
http://api.rubyonrails.org/v4.2.5/classes/Object.html#method-i-try