2015-05-23 187 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])] 
)