In several of my controllers, I have code looking something like this:
@user
.cars.find_by_id(params[:car_id])
.try(:wheels).find_by_id(params[:wheel_id])
.try(:screews).where(id: ids)
This can of course raise the exception: NoMethodError: undefined method `where' for nil:NilClass. I would like to be able to give my user more information about what went wrong, in this case, that the user had no cars with the specified id.
Changing find_by_id to find would cause the above code to raise an ActiveRecord::RecordNotFound exception, which I could handle, but in that case, how do I find out if the cars or the wheels were missing? The RecordNotFound exception doesn't really contain that much information. Is there any good way to handle this type of thing well? Preferably, something that is general enough that I could easily reuse the code in my other controllers.
The ActiveRecord::RecordNotFound exception has a message i.e. Couldn't find User with id=200 so you can use it to tell you which model wasn't found.
Just rescue that exception and use the message to show the information to the user. You could search the model name in the message and show a custom prompt if you want to.