我希望这会奏效:
user_ids = [1, 154, 31908]
query = "SELECT id FROM users WHERE id = ANY (ARRAY[$1])"
ActiveRecord::Base.connection.exec_query(query, "SQL", [[nil, user_ids]])
然而,这会导致异常 TypeError: can't cast Array
.好像Rails can handle an array parameter when using the
where
method of some model但是在进行原始 SQL 查询时是否有任何方法可以使用数组参数,而不涉及 ActiveRecord(除了获取连接)或任何模型?
最佳答案
首先创建一个描述整数数组的可重用复合类型定义:
# Somewhere in the static context
IntegerArray = ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Array.new(ActiveModel::Type::Integer.new).freeze
然后在查询中使用这种类型:user_ids = [1, 154, 31908]
query = "SELECT id FROM users WHERE id = ANY($1)"
params = IntegerArray.serialize(user_ids)
ActiveRecord::Base.connection.exec_query(query, "MyLogLabel", [[nil, params]])
请注意,没有必要使用 PG::TextEncoder
直接也不PG::Connection#exec_params
.仍然需要使用ActiveRecord::ConnectionAdapters::PostgreSQL
因为复合类型不是后端不可知的。
关于ruby-on-rails - 使用针对 PostgreSQL 的数组参数在 Rails 中执行原始 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64894375/