Search code examples
ruby-on-railscontrollers

How can I deal with invalid IDs in before_filter?


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?


Solution

  • If the user_id param does not exist, then find method throw ActiveRecord::RecordNotFound exception. This exception is caught in a before_filter and rendered error. Аll subsequent filters and the index action will not be called.

    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])
      rescue ActiveRecord::RecordNotFound
        # render or redirect_to error
      end
    
    end