安全的 ActiveRecord 之类的查询 [英] Safe ActiveRecord like query

查看:20
本文介绍了安全的 ActiveRecord 之类的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写 LIKE 查询.

I'm trying to write LIKE query.

我读到纯字符串查询不安全,但是我找不到任何文档来解释如何编写安全的 LIKE Hash 查询.

I read that pure string quires aren't safe, however I couldn't find any documentation that explain how to write safe LIKE Hash Query.

有可能吗?我应该手动防御 SQL 注入吗?

Is it possible? Should I manually defend against SQL Injection?

推荐答案

为确保您的查询字符串得到正确清理,请使用数组或哈希查询语法来描述您的条件:

To ensure that your query string gets properly sanitized, use the array or the hash query syntax to describe your conditions:

Foo.where("bar LIKE ?", "%#{query}%")

或:

Foo.where("bar LIKE :query", query: "%#{query}%")

如果query 可能包含% 字符,那么您需要使用sanitize_sql_like 首先:

If it is possible that the query might include the % character then you need to sanitize query with sanitize_sql_like first:

Foo.where("bar LIKE ?", "%#{sanitize_sql_like(query)}%")
Foo.where("bar LIKE :query", query: "%#{sanitize_sql_like(query)}%")

这篇关于安全的 ActiveRecord 之类的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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