ruby 像查询一样的安全 ActiveRecord
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26094430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Safe ActiveRecord like query
提问by Gal Weiss
I'm trying to write LIKE query.
我正在尝试编写 LIKE 查询。
I read that pure string quires aren't safe, however I couldn't find any documentation that explain how to write safe LIKE Hash Query.
我读到纯字符串查询不安全,但是我找不到任何文档来解释如何编写安全的 LIKE Hash 查询。
Is it possible? Should I manually defend against SQL Injection?
是否可以?我应该手动防御 SQL 注入吗?
回答by spickermann
To ensure that your query string gets properly sanitized, use the array or the hash query syntax to describe your conditions:
为确保您的查询字符串得到正确清理,请使用数组或哈希查询语法来描述您的条件:
Foo.where("bar LIKE ?", "%#{query}%")
or:
或者:
Foo.where("bar LIKE :query", query: "%#{query}%")
If it is possible that the querymight include the %character then you need to sanitize querywith sanitize_sql_likefirst:
如果有可能的是,query可能包括%字符,那么你需要消毒query与sanitize_sql_like第一:
Foo.where("bar LIKE ?", "%#{sanitize_sql_like(query)}%")
Foo.where("bar LIKE :query", query: "%#{sanitize_sql_like(query)}%")
回答by Pedro Rolo
Using Arel you can perform this safe and portable query:
使用 Arel,您可以执行此安全且可移植的查询:
title = Model.arel_table[:title]
Model.where(title.matches("%#{query}%"))
回答by Khoga
For PostgreSQL it will be
对于 PostgreSQL,它将是
Foo.where("bar ILIKE ?", "%#{query}%")
回答by Santhosh
You can do
你可以做
MyModel.where(["title LIKE ?", "%#{params[:query]}%"])

