Ruby PG gem使用数组作为exec_params的参数

时间:2015-05-23 05:50:35

标签: ruby-on-rails arrays ruby postgresql pg

我想传递一个像这样的ruby数组值:

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

返回

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

如果我将sql更改为"SELECT $1::int[]",我会PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: "[1, 2]"

有没有办法将ruby数组传递给exec_params并将其转换为PostgreSQL数组?

3 个答案:

答案 0 :(得分:7)

您可以使用编码器执行此操作:

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

答案 1 :(得分:0)

您需要按以下方式执行此操作:

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

答案 2 :(得分:0)

pg_exec_array_params宝石允许这样做:

# Instead of:
# PG::Connection.exec_params(
#   'SELECT ARRAY[$1, $2]'
#   [1, 2]
# )
PgExecArrayParams.exec_array_params(conn, 'select $1', [[1, 2]])
=> [{"array"=>"{1,2}"}]