首页 > 解决方案 > 如何在 Rails 中查询包含单引号的 jsonb 字段和值?

问题描述

我有一个使用 PostgreSQL 运行的 Rails 应用程序。有一个名为 Programs 的表,如下所示:

Program(id: integer, name: string, properties: jsonb)

假设我们有一个名为“Football Club”的程序,其属性如下:

{
  "properties" => 
    {
      "What's your gender?" => "I'm male.",
      "Is your health good?" => "Yes"
    }
}

我的查询是这样的:

# this field and value are OK with the query
field = Is your health good?
value = Yes

Program.where("properties ->> '#{field}') = '#{value}'")

# this field and value causes error with the query since they contain quote (')
field = What's your gender?
value = I'm male.

Program.where("properties ->> '#{field}') = '#{value}'")

我知道问题是由我插入字符串的方式引起的。然而,我找不到解决方案。非常感谢您的帮助。

标签: ruby-on-railspostgresql-9.6

解决方案


推荐阅读