[英]Rails: safe query against stored array
I am having a problem performing a where query against an array field in my Postgres database. 我在对Postgres数据库中的数组字段执行where查询时遇到问题。
In my rails app i have a table called People
. 在我的rails应用程序中,我有一个名为
People
的表。 One column in this is called pets
. 其中的一列称为
pets
。 Now this column contains array values, ie: 现在,此列包含数组值,即:
["dog", "cat", "fish"]
I would like to perform a query that returns all the people that have a pet dog for example. 我想执行一个查询,例如返回所有拥有宠物狗的人。
The solution ive been using so far looks as such 到目前为止,我一直使用的解决方案
People.where("\"pets\" @> '{\"" + checkedPet + "\"}'")
where checkedPet
is a variable and could be "dog" or any other animal. 其中
checkedPet
是变量,可以是“狗”或任何其他动物。
This works but i feel is vulnerable to a SQL injection problem? 这可行,但我感觉很容易受到SQL注入问题的影响?
Is this the case? 是这样吗 If so what is a better and safer solution to avoid it?
如果是这样,那么有什么更好,更安全的方法来避免这种情况?
According to ActiveRecord and PostgreSQL guide you can do the following: 根据ActiveRecord和PostgreSQL指南,您可以执行以下操作:
People.where('? = any("pets")', checkedPet)
Or 要么
People.where('"pets" @> ?', "{#{checkedPet}}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.