Rails 如何用 Rails 安全地进行带有参数的 SQL 语句操作?

linjunhalida · October 10, 2014 · Last by linjunhalida replied at October 11, 2014 · 2259 hits

rails 可以直接执行 sql 操作:

conn = ActiveRecord::Base.connection
c.execute("update posts set comments_count = 0")

但是我要传参数,我们知道,这样是不安全的:

c.execute("update posts set comments_count = #{count}")

最好可以这样:

c.execute("update posts set comments_count = ?", count)

我找了一下,没有看到解决方案:

sanitize_sql

exec_update 找到用法了,应该这样:

c.exec_update("update posts set comments_count = $1", "haha", [[Post.columns_hash[:comments_count], 12]])

最后的参数 binds 会拆分出来反向一个个丢给 Connection.quote,前面的参数是 column,后面的是 value,这样把值 quote 起来。

You need to Sign in before reply, if you don't have an account, please Sign up first.