I have an app with user and events. Each user has several events. When a user wants to see a specific event he will get to this action:
def show
begin
@userEvents = current_user.event
@event = @userEvents.find(params[:id])
rescue ActiveRecord::RecordNotFound
redirect_to :controller => "main", :action => "index"
end
respond_to do |format|
format.html # show.html.erb
format.json { render json: @event }
end
end
If the event is not found for the user it means he played with the URL and the event he is trying to get does not belong to him. I want to either redirect him to the main page or just display the page with an error that the event is not found. If I try to run the code above this error fires:
AbstractController::DoubleRenderError in EventsController#show
What's the best way to fix this?
Put return after redirect
Calling
redirect_to
doesn't return from your action method which is why moving on to therespond_to
block causes theDoubleRenderError
. One way to fix that is with:However, a better solution might be to either rescue from this exception declaratively or just let it propagate to the client. The former look like this:
If you just let the exception fester the user will see the
public/404.html
page in production mode.