2015-05-23 130 views
3

我想通过像这样红宝石数组值PARAM:红宝石PG宝石使用数组与exec_params

sql = "SELECT $1" 
User.connection.raw_connection.exec_params(sql, [[1,2]]) 

如果我改变sql"SELECT $1::int[]"我得到PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: "[1, 2]"这将返回

PG::IndeterminateDatatype: ERROR: could not determine data type of parameter $1 

有没有办法将红宝石数组传递到exec_params并将其转换为PostgreSQL数组?

回答

0

你需要如下做到这一点:

params = [1, 2] 
sql = params.size.times.map { |n| "$#{n+1}::INT" }.join(",") 
User.connection.raw_connection.exec_params("SELECT #{sql}", params) 
4

您可以使用编码器来做到这一点:

raw_connection.exec(
    "select $1::int[]", 
    [PG::TextEncoder::Array.new.encode([1, 2])] 
)