简体   繁体   中英

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)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM