我想知道如何在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'}]
但是有更优雅的方式吗?
答案 0 :(得分:1)
请参阅quote
方法:http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Quoting.html#method-i-quote
我知道你说“一般”,但上面两个查询可以使用ActiveRecord编写,这样你就可以避免自己引用。