转义':'和'?'在Rails的参数化SQL查询

问题描述:

我想知道如何逃避?: SQL查询一般。转义':'和'?'在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开始)

我不问如何逃脱防止注射。我在问什么时候使用参数化查询,导轨会看到?: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'}] 

但有一个更优雅的方式?

+0

我不明白你的问题....... :) –

+0

问题是rails会看到吗?和:bar作为参数而不是字符串。但我希望Rails将它们看作字符串。 – user3381925

+0

你可以使用像Post.where这样的内置函数(“author = \?and title like'%?%'”,@title) – tingel2k

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

我知道你说“一般”,但上述两个查询可以使用ActiveRecord写这样就可以避免不必自己引用的东西。

+0

你能解释更多吗?在这两个例子中,我不知道如何使用引用。目的不是为了防止SQL注入。问题是轨道会看到?和:bar作为参数而不是字符串。 – user3381925