开发者

Rails - Formatting Comma Separated Values for 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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜