简体   繁体   中英

Querying in rails - Double quoted string inside query

I need query like this

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)

  }

But the structure has to be like '{"a":1, "b":"2"}'::jsonb @> '{"b":2}'::jsonb

How do I get the double quote in raw query using the substitution using ? in rails.

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)

But any other ways to get the double quoted string inside raw query?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM