Rails,如何清理 find_by_sql 中的 SQL [英] Rails, how to sanitize SQL in find_by_sql

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

问题描述

有没有办法在rails方法find_by_sql中清理sql?

Is there a way to sanitize sql in rails method find_by_sql?

我已经尝试过这个解决方案:Ruby on Rails:不使用 find 时如何为 SQL 清理字符串?

I've tried this solution: Ruby on Rails: How to sanitize a string for SQL when not using find?

但它失败了

Model.execute_sql("Update users set active = 0 where id = 2")

它抛出一个错误,但执行了 sql 代码并且 ID 为 2 的用户现在拥有一个禁用的帐户.

It throws an error, but sql code is executed and the user with ID 2 now has a disabled account.

简单的 find_by_sql 也不起作用:

Simple find_by_sql also does not work:

Model.find_by_sql("UPDATE user set active = 0 where id = 1")
# => code executed, user with id 1 have now ban

好吧,我的客户要求在管理面板中创建该功能(通过 sql 选择)以进行一些复杂的查询(连接、特殊条件等).所以我真的很想找到_by_sql那个.

Well my client requested to make that function (select by sql) in admin panel to make some complex query(joins, special conditions etc). So I really want to find_by_sql that.

第二次

我想实现不执行邪恶"的 SQL 代码.

I want to achieve that 'evil' SQL code won't be executed.

在管理面板中,您可以输入 query -> Update users set admin = true where id = 232 并且我想阻止任何 UPDATE/DROP/ALTER SQL 命令.只是想知道,在这里你只能执行 SELECT.

In admin panel you can type query -> Update users set admin = true where id = 232 and I want to block any UPDATE / DROP / ALTER SQL command. Just want to know, that here you can ONLY execute SELECT.

经过一些尝试,我得出结论 sanitize_sql_array 不幸的是不要这样做.

After some attempts I conclude sanitize_sql_array unfortunatelly don't do that.

有没有办法在 Rails 中做到这一点??

Is there a way to do that in Rails??

抱歉造成混乱..

推荐答案

试试这个:

connect = ActiveRecord::Base.connection();
connect.execute(ActiveRecord::Base.send(:sanitize_sql_array, "your string"))

您可以将其保存在变量中并用于您的目的.

You can save it in variable and use for your purposes.

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

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