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

Ree*_*Law 3 ruby arrays postgresql ruby-on-rails pg

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

sql = "SELECT $1"
User.connection.raw_connection.exec_params(sql, [[1,2]])
Run Code Online (Sandbox Code Playgroud)

这回来了

PG::IndeterminateDatatype: ERROR:  could not determine data type of parameter $1
Run Code Online (Sandbox Code Playgroud)

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

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

Ben*_*jie 7

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

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