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})"
精彩评论