In a Rails (5.2) app with PG (10) as the database, I need to perform a raw SQL query.
In the query, I need to add aWHERE clause that checks the qp.id is among project.qp_ids which are stored as an array of strings.
t.text :qp_ids, array: true, default: []
I have tried several solutions, among which the following
" ... WHERE qp.id = ANY #{project.qp_ids}"
" ... WHERE qp.id = ANY #{project.qp_ids.join(', ')}"
" ... WHERE qp.id = ANY ARRAY(#{project.qp_ids.join(', '))}"
" ... WHERE qp.id = IN (#{project.qp_ids.join(', ')})"
But all produce a PG::SyntaxError.
What is the right way to interpolate a PG array?
UPDATE1
The code below works but is very ugly,
" ... WHERE qp.id = IN (#{self.quality_process_ids.map {|id| "'#{id}'"}.join(',')})"
id.project.qp_idsas Ruby string, andqp.idas a columnidof tableqp. It's hard to say what you want to get. Areqpandproductstables in PG? What are their fields?qp.idis a column andproject.qp_idsis the attributeqp_idsof the ActiveRecordprojectpassed to the method responsible to build the query. Thanks.where('id = any(array[?])', project.qp_ids)just fine. If you do need to build this by hand then you need to properly quote each element ofqp_idsbefore you join them with commas and you'll need an extra set of parentheses (i.e.qp.id = any(array[...])).