Rails中如何获取变量替换后的SQL语句?

问题描述 投票:0回答:1

我正在使用 Rails 7.1.2,我正在尝试弄清楚如何让 Rails/ActiveRecord 将变量插值到 SQL 字符串中,并将生成的 SQL 返回给我。这是我尝试过的:

>> User.connection.to_sql("select * from users where id = $1", [1])
=> "select * from users where id = $1"
>> User.connection.to_sql("select * from users where id = ?", [1])
=> "select * from users where id = ?"
>> User.connection.to_sql("select * from users where id = :id", { id: 1 })
=> "select * from users where id = :id"
>> User.connection.to_sql("select * from users where id = :id", [{ id: 1 }])
=> "select * from users where id = :id"

此方法的文档不清楚是否应该插入绑定参数,它只是说:

https://api.rubyonrails.org/v7.0.8/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-to_sql

将 arel AST 转换为 SQL

当他们说“SQL”时,我不知道他们是否指的是带有插值参数的 SQL,但我不知道如果不插值参数,为什么该方法会接受绑定参数。

我正在寻找查询中将被替换的参数的任何变体,因此我会将绑定参数的值插入到结果中,如下所示:

>> User.connection.to_sql("select * from users where id = $1", [1])
=> "select * from users where id = 1"
ruby-on-rails activerecord
1个回答
0
投票

您正在寻找

sanitze_sql
和来自
ActiveRecord::Sanitization::ClassMethods
的朋友:

User.sanitize_sql(['select * from users where id = ?', 1])
# select * from users where id = 1

User.sanitize_sql(['select * from users where id = :id', id: 11])
# select * from users where id = 11

User.sanitize_sql(['select * from users where name = :name', name: "G'Kar"])
# select * from users where name = 'G''Kar'
© www.soinside.com 2019 - 2024. All rights reserved.