bos*_*cko 4 ruby postgresql activerecord ruby-on-rails rails-activerecord
我正在尝试使用exec_query通过绑定引入的值来运行任意查询,并且遇到了意外错误。
在控制台中运行
sql = 'SELECT * FROM foobars WHERE id IN (?)'
name = 'query_name_placeholder'
binds = [FooBar.first]
ActiveRecord::Base.connection.exec_query sql, name, binds
产生此错误:
Account Load (7.9ms) SELECT "foobars".* FROM "foobars" ORDER BY "foobars"."id" ASC LIMIT 1
PG::SyntaxError: ERROR: syntax error at or near ")"
LINE 1: SELECT * FROM foobars WHERE id IN (?)
^
: SELECT * FROM foobars WHERE id IN (?)
ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: syntax error at or near ")"
LINE 1: SELECT * FROM foobars WHERE id IN (?)
^
: SELECT * FROM accounts WHERE id IN (?)
from /Users/foo_user/.rvm/gems/ruby-2.2.4@foo_project/gems/activerecord-4.2.3/lib/active_record/connection_adapters/postgresql_adapter.rb:641:in `prepare'
看来绑定语法被忽略了吗?我也尝试... WHERE id = ?过,但无济于事。
Mic*_*ael 11
亩太短,使您无法参与其中。作为参考,这里是方法的文档:https : //apidock.com/rails/ActiveRecord/ConnectionAdapters/DatabaseStatements/exec_query
他是对的,因为您将需要使用基础数据库的绑定语法在SQL字符串中设置绑定变量。对于Oracle,这:1, :2对于PostgreSQL,这是$1, $2...第一步。
第二步是您需要构建绑定对象,它们是QueryAttribute对象,不仅是要传递的值。这有点笨拙,但是下面是一个示例:
binds = [ ActiveRecord::Relation::QueryAttribute.new(
"id", 6, ActiveRecord::Type::Integer.new
)]
ApplicationRecord.connection.exec_query(
'SELECT * FROM users WHERE id = $1', 'sql', binds
)
Run Code Online (Sandbox Code Playgroud)
我花了整整一天时间进行单元测试和源代码,试图弄清楚这一点。