eibersji
eibersji

Reputation: 1216

how to insert an array of strings to sql query in ruby

I have this query in ruby:

  sql = "SELECT variants.id,
                      code,
                      regular_price,
                      price_before_sale
                FROM  variants
                WHERE variants.code IN (#{context.codes.join(",")})"

where context.codes = ['PRDCT-1','PRDCT-2']

now context.codes becomes (PRDCT1,PRDCT2) inside the sql query because of the .join but what I want to happen is ('PRDCT1','PRDCT2') what am I missing?

EDI: I have tried to do (#{context.codes.join("','")}) but it returns (PRDCT1','PRDCT2)

Upvotes: 0

Views: 841

Answers (2)

Amadan
Amadan

Reputation: 198324

Don't do that. Bobby Tables is watching. Instead, provide the adequate number of placeholders:

sql = "SELECT variants.id,
                      code,
                      regular_price,
                      price_before_sale
                FROM  variants
                WHERE variants.code IN (#{context.codes.map { "?" }.join(",")})"

and then provide *context.codes in statement parameters.

Upvotes: 8

eibersji
eibersji

Reputation: 1216

I got it. I added single quotes to ('#{context.codes.join("','")}')

Upvotes: -1

Related Questions