Search code examples
ruby-on-rails-3controllerbefore-filterrescue

rails if else check fails then rescue


I have 2 methods in my controller for finding the user (notice the enabled_only scope):

before_filter :find_user, :only => :show
before_filter :find_any_user, :only => [:edit, :update, :destroy]

def find_user
  @user = User.enabled_only.find(params[:id])
rescue ActiveRecord::RecordNotFound
  flash[:alert] = "The user you were looking for could not be found"
  redirect_to root_path
end

def find_any_user
  @user = User.find(params[:id])
rescue ActiveRecord::RecordNotFound
  flash[:alert] = "The user you were looking for could not be found"
  redirect_to root_path
end

Surely these could be merged into one method that checks whether :action == 'show' but I couldn't get the rescue to catch the error. I tried something like the following but it didn't work:

before_filter :find_user, :only => [:show, :edit, :update, :destroy]

def find_user
  @user = if :action == 'show'
    User.enabled_only.find(params[:id])
  else
    User.find(params[:id])
  end
rescue ActiveRecord::RecordNotFound
  flash[:alert] = "The user you were looking for could not be found"
  redirect_to root_path
end

Please advise on how this can be done.

Thanks


Solution

  • You need to wrap the code you want to 'protect' between a beginand a rescue

    before_filter :find_user, :only => [:show, :edit, :update, :destroy]
    
    def find_user
      begin
        @user = if :action == 'show'
          User.enabled_only.find(params[:id])
        else
          User.find(params[:id])
        end
      rescue ActiveRecord::RecordNotFound
        flash[:alert] = "The user you were looking for could not be found"
        redirect_to root_path
      end
    end
    

    and by the way your test :action == 'show' can never be true. :action is a symbol which value is :action, its value will never change, same for 'show', its value will never change. I'm not sure what's the best way to achieve this but you could do but you could do if params[:action] == "show"