How can I deal with invalid identifiers in before_filter?

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 parameter user_iddoes not exist, @user will be nil.I think it is not:

def index
   if @user
      @some_objects = @user.objects.all
   else
      # ?
   end
end

The code would look ugly, having all these checks in my controller ... not to mention that I will have to duplicate a lot of logic if other controllers are similar to this one. How do you deal with these cases?

+3
source share
4 answers

If the parameter user_iddoes not exist, then findthe throw method throws an ActiveRecord::RecordNotFoundexception. This exception gets into the before_filter file and is rendered. The following subsequent filters and action indexwill 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
+2
source

, :

private
def find_user
  @user = User.find_by_id(params[:user_id])
  redirect_to where_you_want_to_go_when_no_user_url unless @user #for example login page
end

@user, @some_objects ( , ), before_filter:

def get_some_objects
  @some_objects = @user.present? ? @user.objects.all : []
end

( some_objects):

def set_variables
  @user = User.find_by_id(params[:user_id])
  if @user
    @some_objects = @user.objects.all
  else
    redirect_to where_you_want_to_go_when_no_user_url
  end
end

, .

EDIT: 'find' 'find_by_id', , id null, .

+1

- : inherited_resources

, , , .

, , . .

+1

, AR , RecordNotFound. - :

irb(main):025:0> begin
irb(main):026:1* Location.find 100
irb(main):027:1> rescue ActiveRecord::RecordNotFound => e
irb(main):028:1> puts "Oops: #{e.message}"
irb(main):029:1> end
Oops: Couldn't find Location with ID=100
=> nil

If you want to apply something to all controllers, you probably should consider adding your method to ApplicationController ...

0
source

All Articles