如何在Rails 4中清理原始SQL [英] How to sanitize raw SQL in Rails 4

查看:67
本文介绍了如何在Rails 4中清理原始SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails 3中,我可以使用 sanitize_sql_array 在需要原始SQL查询的某些情况下清理原始SQL。但这似乎已在Rails 4中删除,或者没有删除太多,而是移至ActiveRecord :: Sanitization。但是,我现在不知道如何调用 sanitize_sql_array ,那么在Rails 4中清理原始SQL的最佳方法是什么?

In Rails 3 I could use sanitize_sql_array to sanitize raw SQL for those occassional moments where a raw SQL query is needed. But this appears to have been removed in Rails 4, or not so much removed, but moved to ActiveRecord::Sanitization. However, I can not figure out how to call sanitize_sql_array now, so what's the best way to sanitize raw SQL in Rails 4?

我想澄清一下,我在这里谈论的是完整的原始SQL查询,而不是使用Rail的模型。我知道这不是最佳做法,这只是我要针对此特定查询执行的操作,因为它无法由Rails的漂亮ActiveRecord接口表示(请相信我,我已经尝试过)。

I want to clarify that I am talking about a full raw SQL query here, not using Rail's models. I'm aware that this is not best practice, this is just what I have to do for this specific query since it can't be represented by Rails's nice ActiveRecord interface (Trust me, I've tried).

这里是一个示例调用,它显然比我的查询实际看起来简单:

Here is a sample call, which is obviously simpler than what my query actually looks like:

query = "SELECT * FROM users 
LEFT OUTER JOIN posts ON users.id=posts.user_id
AND posts.topic_id = '#{topic.id}'" 
# ^- Obviously bad and very vulnerable, this is what we're trying to fix
ActiveRecord::Base.connection.select_all(query)

$ b的目的$ b

推荐答案

如果您确实需要编写原始SQL,则可以使用 quote 进行清理:

If you really need to write raw SQL you can use quote to sanitize it:

conn = ActiveRecord::Base.connection
name = conn.quote("John O'Neil")
title = conn.quote(nil)
query = "INSERT INTO users (name,title) VALUES (#{name}, #{title})"
conn.execute(query)

这篇关于如何在Rails 4中清理原始SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆