Let’s say my controller looks like this:
class MyController < ApplicationController
before_filter :find_user,:only => [:index,:create,:update,:destroy]
def index
@some_objects = @user.objects.all
end
...
private
def find_user
@user = User.find(params[:user_id])
end
end
If the user_id param does not exist, @user will be nil.I think this is not the way:
def index
if @user
@some_objects = @user.objects.all
else
# ?
end
end
The code would look uglier having all these checks in my controller … not to mention I’d have to duplicate a lot of the logic if other controllers are similar to this one.
How do you deal with these cases?
If the
user_idparam does not exist, thenfindmethod throwActiveRecord::RecordNotFoundexception. This exception is caught in a before_filter and rendered error. Аll subsequent filters and theindexaction will not be called.