What is it the best and safe way to get a string from a user and use it in the WHERE
statement of a query.
Let's say that I have a Model named DB, which contains the columns c1
and c2
. I want the user to be able to give me a string like str="c1: value1"
or str="c1: value1, c2: value2"
so to use it to perform a find ( DB.find(str)
). Of course I don't want him/her to be able to perform SQL injection . Is there an elegant way?
The most important thing to avoid here is putting the user response directly into a where clause. So do not do something like DB.where("c1 = value"). Instead you can rely on rails built in sql sanitizing, by doing something like
DB.where("c1 t = ?", value)
The AR documentation is really clear on this. http://guides.rubyonrails.org/active_record_querying.html#pure-string-conditions
If your string format is fixed, then you can convert it to a Hash
, and then can apply it to the #where
clause.
string = "c1: value1, c2: value2"
hash = Hash[*string.split(/[,:]/).map(&:strip)]
DB.where(hash)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.