3

I am trying to create a dynamic query based on User inputs

if a
  conditions << ["fname like (?)"]
  sql_params <<  "abc"
end
if b
  conditions << ["lname like (?)"]  
  sql_params <<  "def"  
end
if c
  cconditions << ["middle like (?)"]  
  sql_params <<  "xyz"   
end

results = Model.where(conditions.join(' AND '), sql_params)

While the conditions get in correct syntax, the sql_params are listed as an array. This forms the below query

Model.where("fname like (?) AND lname like (?) AND middle like (?)", ["abc","def","xyz"])

while what I need is

Model.where("fname like (?) AND lname like (?) AND middle like (?)", "abc","def","xyz")

I tried several map/join etc options on the sql_params array but nothing worked.

2 Answers 2

4

Are you sure you need to produce exactly this?

Model.where("fname like (?) AND lname like (?) AND middle like (?)", "abc","def","xyz")

Something of the form:

Model.where('expr1 AND expr2 AND expr3')

is equivalent to:

Model.where('expr1').where('expr2').where('expr3')

so why not build the query piece by piece rather than messing around with strings? Something like this:

query = Model.all
query = query.where('fname  like ?', 'abc') if a
query = query.where('lname  like ?', 'def') if b
query = query.where('middle like ?', 'xyz') if c

will give you the same result.

Sign up to request clarification or add additional context in comments.

Comments

3

You need to pass sql_params with * (known as splat operator) i.e.

results = Model.where(conditions.join(' AND '), *sql_params)

1 Comment

You are a life saver! Thanks so much. I spent so much time on this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.