逃避':'和'?'在Rails中的参数化SQL查询中

时间:2015-06-19 19:10:38

标签: mysql sql ruby-on-rails

我想知道如何在SQL查询中逃避?:

这些只是任意的例子:

Post.find_by_sql ["SELECT title, author, content FROM post where author = ? AND RIGHT(content, 1) = '?'", @author]

(查找帖子以?结尾)

Post.find_by_sql ["SELECT title, author, content FROM post where author = :author AND title LIKE 'Foo:bar%'", {author:@author}]

(查找帖子以foo:bar开头)

我不会问如何逃避以防止注射。我问我何时使用参数化查询,rails会将?:some_var视为参数。但是,如果我想将?:stuff用作查询的一部分,该怎么办?我如何逃避它们,以便Rails将它们视为字符串,而不是试图找到匹配的参数?

我知道解决方案是编写这两个查询,如:

Post.find_by_sql ["SELECT title, author, content FROM post where author = ? AND RIGHT(content, 1) = ?", @author, '?']

Post.find_by_sql ["SELECT title, author, content FROM post where author = :author AND title LIKE CONCAT(:name, '%')", {author:@author, name:'foo:bar'}]

但是有更优雅的方式吗?

1 个答案:

答案 0 :(得分:1)

请参阅quote方法:http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Quoting.html#method-i-quote

我知道你说“一般”,但上面两个查询可以使用ActiveRecord编写,这样你就可以避免自己引用。