0

我有一种情况,我需要允许从表单手动构建 SQL。我有这样的事情:

SomeModel.where("id in (#{custom_sql})")

custom_sql像这样的选择语句在哪里:

SELECT u.id FROM some_model u WHERE country_iso = 'AU'

我希望能够捕获当 where 子句中存在无效 SQL 时引发的 StatementInvalid 异常,但我不知道该怎么做。

begin
  SomeModel.where("id in (#{custom_sql})")  
rescue 
  puts "Error"
end

但它不断地失败而没有错误。然而rails c,当我这样做时User.where("id in (#{custom_sql})"),它会正确出错。有任何想法吗?

4

3 回答 3

2

使用 .检查您的 SQL 语句的有效性ActiveRecord::Base.connection.execute。如果您的语句无效,它将引发错误。

begin
  ActiveRecord::Base.connection.execute custom_sql
  User.where("id in (#{custom_sql})")  
rescue 
  puts "Error"
end
于 2013-06-04T01:16:28.397 回答
1

首先,您的示例不清楚或具有误导性(可能是由于您努力掩盖实际型号名称)

因为如果你真的想运行你提议的场景,你得到的查询将是

select * from some_model where id in (select u.id from some_model u where country_iso = "AU"

(ignoring the fact that your country_iso field is ambiguous) You are just running

SomeModel.where country_iso: "AU"

So you'll need to refine your example and properly illustrate your problem, because while @zeantsoi suggests a way to help you validate your statement(s), I agree with @phoet that you are probably approaching the situation incorrectly.

于 2013-06-04T16:49:55.607 回答
0

首先,这是最好的sql注入。你应该重新考虑你想要完成的任何事情。

其次,User.where返回一个关系。关系是懒惰的。惰性语句尚未执行。所以如果你这样做User.where(...).all应该会有所帮助。

于 2013-06-04T01:07:20.707 回答