user1515295
user1515295

Reputation: 1211

Rails before filter not redirecting

Any reason why this before action would not redirect when @user is nil?

def set_user
  @user ||= User.find(params[:id])
  redirect_to "/errors/404" unless @user
end

I can actually see it redirecting in the log (pasted below).

Redirected to http://localhost:3000/errors/404

but instead of rendering that error page and routing away from the controller action, it completes the action and causes an error saying @user is nil.

Upvotes: 0

Views: 34

Answers (1)

fivedigit
fivedigit

Reputation: 18682

The find method never returns nil. Instead, if a record with that ID doesn't exist, it throws an ActiveRecord::RecordNotFound error.

The easiest fix would be to use rescue_from:

class YourController < ApplicationController
  rescue_from ActiveRecord::RecordNotFound, with: :redirect_to_not_found
  # Other code

  private
  def set_user
    @user ||= User.find(params[:id])
  end

  def redirect_to_not_found
    redirect_to "/errors/404"
  end
end

Now, the redirect_to_not_found method will be called whenever a user isn't found.

Upvotes: 1

Related Questions