4

为什么我无法通过以下方法拯救任何东西?

def get_things
  begin
    things= @member.things.where("id>?",params[:id])
  rescue ActiveRecord::StatementInvalid
    render( inline: "RESCUED ActiveRecord::StatementInvalid" )
    return
  rescue
    render( inline: "RESCUED something" )
    return
  end
  render( inline: "#{things.first.title}" )
end

当使用有效的 id 调用时,它可以工作:

$  curl -vd "id=3" http://localhost:3000/get_things

但如果我传错了,例如:

$  curl -vd "id=3,0" http://localhost:3000/get_things
$  curl -vd "id='3'" http://localhost:3000/get_things

异常未获救:

< HTTP/1.1 500 Internal Server Error
<h1>
  ActiveRecord::StatementInvalid
    in ApplicationController#get_things
</h1>
<pre>PG::Error: ERROR:  invalid input syntax for integer: &quot;'3'&quot;

仅当渲染发生在开始/救援块内时

def get_things
  begin
    things= @member.things.where("id>?",params[:id])
    render( inline: "#{things.first.title}" )
  rescue ActiveRecord::StatementInvalid
    render( inline: "RESCUED ActiveRecord::StatementInvalid" )
    return
  end
end

它按预期工作:

$ curl -vd "id='3'" http://localhost:3000/get_things
  < HTTP/1.1 200 OK
  RESCUED ActiveRecord::StatementInvalid
4

2 回答 2

9

据我所知,things在您的情况下,将是一个包含查询信息的类,但是在您尝试访问基于查询的元素(如things.first)之前,查询不会被执行。

things= @member.things.where("id>?",params[:id]) # query not run
things= things.order("id desc") # still not run
things.first.title # now the query runs, the statement can be invalid

这就是它无法挽救的原因,因为在您的渲染行中,发生异常的地方,而不是在创建things.

这应该没问题:

def get_things
  begin
    things= @member.things.where("id>?",params[:id])
    thing_title = things.first.title
  rescue ActiveRecord::StatementInvalid
    render( inline: "RESCUED ActiveRecord::StatementInvalid" )
    return
  rescue
    render( inline: "RESCUED something" )
    return
  end
  render( inline: "#{thing_title}" )
end
于 2012-07-14T13:35:16.753 回答
-1

您可以将参数更改为 int:

params[:id] = params[:id].to_i if params[:id].present?
things= @member.things.where("id>?",params[:id])

或者您可以在以下位置添加参数验证器config/routes.rb

resources :things, :constraints => {:id => /\d+/}
于 2012-07-14T13:27:03.710 回答