4

Im trying to create a sql query dynamically with the following syntax:

Company.joins(:founder_persons)
       .where("people.first_name like people[:first_name]", {people: {first_name: 'm%'}})

But running this on the rails console gives me TypeError: can't quote Array. Im guessing this is not how we use the where string? What's the right way to fix this error? Thanks.

2 Answers 2

5

One reason this error can occur is with a nested array used as SQL value.

Example:

Article.where(author: ['Jane', 'Bob'])

works, but:

Article.where(author: ['Jane', ['Bob']])

would give the error. A quick fix would be to run flatten on the array.

(Mentioning this since this page comes up when searching for the confusing error "Can't quote array".)

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

1 Comment

That was exactly it. You the man.
3

You could bind any value and then assign it, this way they should coincide in numbers, like:

Model.joins(:join_table)
     .where('models.first_attribute LIKE ? AND models.second_attribute LIKE ?', value_for_first_attr, value_for_second_attr)

If using an array you should access each index you want to compare, or you can precede a splat *, and specify just one value, like:

Model.joins(:join_table)
     .where('models.first_attribute LIKE ? AND models.second_attribute LIKE ?', *array_of_values)

Note although this way you're passing the "whole" array it should also coincide in size or numbers, otherwise it'd raise an ActiveRecord::PreparedStatementInvalid error depending if there are more or less elements than needed.

10 Comments

ooooo yaas, let me try xD
I'd like to know if is what you meant, because of 'm%' I'm not sure.
oh yes, there is a problem with this, actually the query is being made dynamically so the where string could be 'this like ? AND this like ? AND this like ? so could I pass an array of values instead of comma separated values after the string like .where(...string... , [people[:first_name], people[:last_name]...])
Yes, you can bind the values the same way if they're more than one, note you don't need to use an array, just pass them separated by comma, just they must coincide.
that's the problem, i can't pass them separated by commas. I have an array of all the values. So for example I have this string: this like ? AND that like ?' I have an array of 2 values for the 2 ? named val_arr. So how would I .where('this like ? AND that like ?', comma_separated_each_element_of_val_arr) ?
|

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.