如何在Rails 4中清理原始SQL

编程入门 行业动态 更新时间:2024-10-27 05:29:07
本文介绍了如何在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

本文发布于:2023-10-24 15:01:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524253.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原始   如何在   Rails   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!