redirect_to在if语句中不能按预期工作

Rub*_*tic 4 redirect ruby-on-rails ruby-on-rails-4

试图找出为什么我的nil检查在调用没有param的方法或者没有产生记录的param id时失败.

@game       = Game.where(:id => params[:id]).first

if @game.nil?
  redirect_to root_path
end
Run Code Online (Sandbox Code Playgroud)

在控制台中这很好用.

>> pp @game.nil?
=> true
Run Code Online (Sandbox Code Playgroud)

在应用程序中,这失败了(它永远不会重定向!),为什么?

编辑1:

在控制台中(param id为nil或不存在记录值):这有效:

unless Game.exists?(params[:id])
  raise('ok')
end
Run Code Online (Sandbox Code Playgroud)

但不是在现实生活中的应用程序:(我几乎用各种方式检查记录是否存在或有效,代码只是通过此检查并继续原样

编辑2:

看看其他一些代码,我注意到我使用了一个返回语句,IT似乎用它解决了这个问题.

作品:

unless Game.exists?(params[:id])
  redirect_to root_path
  return
end
Run Code Online (Sandbox Code Playgroud)

失败:

unless Game.exists?(params[:id])
  redirect_to root_path
end
Run Code Online (Sandbox Code Playgroud)

不太确定为什么它需要在redirect_to explicit之后返回

Dan*_*yel 12

如果redirect_to指令不是控制器中的最后一条指令,则重定向永远不会发生.

if @game.nil?
  redirect_to root_path
  return
end

render @game
Run Code Online (Sandbox Code Playgroud)

如果没有回归,那redirect_to将被一个覆盖render.你必须这样看:Rails不会立即重定向到redirect_to指令.它将某处的指令集,一旦你的控制器返回,它将检索,如果有一组动作做,如果没有,它会跳转到默认操作("渲染动作视图")

如果有一个警告,如果你有多个redirects/renders,你可能会覆盖你的行动,但这可能会很好,但除此之外,这是完全正常的行为.

问候.

编辑

另外,如果您使用的是Rails 4,请使用Game.find_by(id: params[:id])而不是Game.where(id: params[:id]).first.
如果您只是想检查一下存在Game.exists?(params[:id]),就像其他人提到的那样,这是一种很好的方式.Game.find(params[:id])如果id找不到,将抛出错误.一个很好的提示是使用slug,因为人们可能猜到你的游戏ID,这基本上是一个安全漏洞.