开发者

Rails - Formatting Comma Separated Values for SQL

开发者 https://www.devze.com 2023-02-16 07:15 出处:网络
How would I take this following comma separated string: 111, 222, 333 and have it properly formatted to the following sql:

How would I take this following comma separated string:

111, 222, 333

and have it properly formatted to the following sql:

select all from table where id IN ('111', '222', '333')

I'm using prepared statement with find_by_sql. Please h开发者_如何学运维elp.


You can format the ids using map:

'111,222,333'.split(',').map { |id| "'#{id}'" }.join(',')

There is a method to wrap a string with characters, but it escapes me. Hence, the ugly map block.


string = "111, 222, 333"
ids = string.gsub(/(\d)/, '\'\1\'')
query = "select all from table where id IN (#{ids})"
0

精彩评论

暂无评论...
验证码 换一张
取 消