Alexey
Alexey

Reputation: 3637

Rails, passing an array as criteria to query

I'm calling the database based on the criteria passed from the view, so it has to be dynamic.

Let's say I have 2 arrays:

columns = ['col1', 'col2', 'col3']
vals = ['val1', 'val2', val3']

The query is easy to create, I can do concatenation, like

query = columns[0] + " = (?) AND" + ...

But what about the parameters?

@finalValues = MyTable.find(:all, :conditions => [query, vals[0], vals[1]... ])

But I don't know how many parameters I will receive. So while the query problem is solved with a for loop and concatenation, can I do something like:

@finalValues = MyTable.find(:all, :conditions => [query, vals])

And rails will understand that I'm not passing an array for an IN (?) clause, but to split the values for every individual (?)?

Or is my only option to do a full raw string and just go with it?

Upvotes: 0

Views: 156

Answers (1)

Naren Sisodiya
Naren Sisodiya

Reputation: 7288

you can create condition array with query as first element and append all val element to it.

query = columns.map {|col| "#{col} = ?"}.join(" AND ")
@finalValues = MyTable.find(:all, :conditions => [query, *vals])

point of caution the columns and vals should have equal number of elements.

Upvotes: 2

Related Questions