Rails custom request string

What is the best and safest way to get the string from the user and use it in the WHERE

query statement .

Let's say that I have a model named DB that contains 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 that I can use it to do a search ( DB.find(str)

). Of course, I don't want him / her to be able to perform SQL injection . Is there an elegant way?

+3


source to share


2 answers


The most important thing to avoid here is to postpone the user's response directly in the where clause. So don't do something like DB.where ("c1 = value"). Instead, you can rely on the rails built into sql-sanitizing by doing something like

DB.where ("c1 t =?", Value)



The AR documentation is really clear. http://guides.rubyonrails.org/active_record_querying.html#pure-string-conditions

+3


source


If your string format is fixed, you can convert it to Hash

and then apply it to the sentence #where

.



string = "c1: value1, c2: value2"
hash = Hash[*string.split(/[,:]/).map(&:strip)]
DB.where(hash)

      

0


source







All Articles