【问题标题】:rails if else check fails then rescuerails if else 检查失败然后救援
【发布时间】:2012-10-29 22:38:14
【问题描述】:

我的控制器中有 2 种方法用于查找用户(注意 enabled_only 范围):

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

当然,这些可以合并为一种方法来检查:action == 'show' 是否存在,但我无法通过救援来捕获错误。我尝试了以下类似的方法,但没有成功:

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

请告知如何做到这一点。

谢谢

【问题讨论】:

    标签: ruby-on-rails-3 controller before-filter rescue


    【解决方案1】:

    您需要将要“保护”的代码封装在 beginrescue 之间

    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
    

    顺便说一句,您的测试:action == 'show' 永远不会是真的。 :action 是一个符号,其值为:action,它的值永远不会改变,'show' 也是如此,它的值永远不会改变。我不确定实现这一目标的最佳方法是什么,但你可以做到,但你可以做到if params[:action] == "show"

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-12
    • 2023-01-13
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    相关资源
    最近更新 更多