【问题标题】:Querying in rails - Double quoted string inside query在 rails 中查询 - 查询中的双引号字符串
【发布时间】:2019-01-08 19:04:51
【问题描述】:

我需要这样的查询

scope :find_email_usage, -> (id) {
    where("EXISTS ((with filter_table as (select id, jsonb_array_elements(jsonb_array_elements(filters) -> 'criteria') filter_json) select 1 from filter_table where filter_json @> '{\"mail_id\": ?}'))", id.to_s, id.to_s)

  }

但结构必须像'{"a":1, "b":"2"}'::jsonb @> '{"b":2}'::jsonb

如何使用替换在原始查询中获得双引号?在铁轨上。

where("EXISTS ((with filter_table as (select id, jsonb_array_elements(jsonb_array_elements(filters) -> 'criteria') filter_json) select 1 from filter_table where filter_json @> '{\"mail_id\": "#{id.to_s}"))", id.to_s)

但是还有其他方法可以在原始查询中获取双引号字符串吗?

【问题讨论】:

    标签: ruby-on-rails postgresql activerecord ruby-on-rails-5


    【解决方案1】:

    最简单的方法是构建一个 Ruby 哈希,将其转换为 JSON,然后将该字符串提供给查询:

    where('EXISTS ((... where filter_json @> ?::jsonb))', { 'mail_id' => id.to_s }.to_json)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-20
      • 2012-11-18
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 2017-12-05
      相关资源
      最近更新 更多