【问题标题】:Passing a string in where clause in Rails is always quoted在 Rails 的 where 子句中传递字符串总是被引用
【发布时间】:2023-12-02 22:23:01
【问题描述】:

我正在尝试以编程方式编写 .where() 子句。

看起来像

Post.where("description ?", @composite)

其中@composite 是之前构造的字符串。它可能类似于= 'ABCD'IS LIKE 'ABCD' 等。

问题在于生成的 SQL 始终是单引号。例如:

Post Load (0.2ms)  SELECT `posts`.* FROM `posts` WHERE (description 'IS LIKE "ABCD"')

有没有办法“取消引用”它?

【问题讨论】:

    标签: sql ruby-on-rails where-clause quotes composition


    【解决方案1】:

    =IS LIKE 不应是您传入的字符串的一部分。

    它被单引号引用,因为这正是 ? 所做的:SQL 安全引用。

    如果您想自己完全构建 SQL,那么就这样做,例如,

    Post.where("description #{@composite}")
    

    您需要自己清理字符串,这很容易,因为大概您正在使用输入构造 =IS LIKE 部分。

    【讨论】:

    • 这就是我试图解决的问题 :) Post.where("description #{@composite}") 不适合 SQL 注入。
    • @valk 但是您不能按照您尝试的方式进行操作,? 明确保护输入值。如果您不打算使用内置机制,则需要自己保护它。
    • 所以答案是,Rails 不知道如何清理除 SQL 值之外的任何内容:)
    • @valk 没有其他东西需要消毒。
    • 对,但是如果对整个块进行消毒,会节省时间,不是吗?
    【解决方案2】:

    使用这个:

    Post.where("description #{@composite}")
    

    【讨论】:

    • 那么你必须改变@composite创建
    • 喜欢试试这个:search_string = "ABCD" exact_match = false Post.where("description #{exact_match ? '=' : 'LIKE'} ?", search_string)
    最近更新 更多