Hi
say i have an update function of Sample with
authorize @sample, :update?
sometimes @sample is nil, because the client sent non existing sample id.
how can I render an error message and not crash with exception of
"unable to find policy of nil" ?
thanks a lot
This might be a good situation to use a null object?
hi and thanks. yes, i can "check" for nil in many ways, but if it is nil, what should i "authorize" ? (as i must authorize something)
thanks again
@dowi What @ingemar is saying is that you can use a null object, that is, a NullSample object that implements update and always returns false. It could even be a generic object NullObject that you use in other controllers too, and you could have a NullObjectPolicy that returns true or false for all actions, based on what makes sense in your application. Since Pundit infers the policy form the object, your action will be properly authorized.
# Model
class NullObject
def update
false
end
end
# Policy
class NullObjectPolicy < ApplicationPolicy
def update?
false # or true if you want to authorize and handle response later
end
end
# Controller
@sample = Sample.find_by(id: params[:id]) || NullObject.new
@carlesjove thanks a lot! I got it from your explanation. thanks for the code sample
Most helpful comment
@dowi What @ingemar is saying is that you can use a null object, that is, a
NullSampleobject that implementsupdateand always returnsfalse. It could even be a generic objectNullObjectthat you use in other controllers too, and you could have aNullObjectPolicythat returnstrueorfalsefor all actions, based on what makes sense in your application. Since Pundit infers the policy form the object, your action will be properly authorized.