【问题标题】:Rails on JSONB 'where' multiple search terms in nested array of objects嵌套对象数组中 JSONB 'where' 多个搜索词的 Rails
【发布时间】:2021-04-02 21:43:45
【问题描述】:

我在 Rails 中有一个表配置文件的 jsonb 列,其结构如下

add_column :profile, :properties, :jsonb, default: {}

user.build_profile(
  properties: {
    languages: [
        {name: "German", level: 3}, 
        {name: "Russian", level: 2},
        {name: "English", level: 3}
    ],
    skills: ['Alpha', 'Beta', 'Gamma']
  }
)

user.build_profile(
  properties: {
    languages: [
        {name: "German", level: 2}, 
        {name: "Russian", level: 3},
        {name: "Spanish", level: 3}
    ],
    skills: ['Alpha','Beta']
  }
)


user.build_profile(
  properties: {
    languages: [
        {name: "Italian", level: 2}, 
        {name: "Spanish", level: 3}
    ],
    skills: ['Gamma']
  }
)

我可以像这样检索一种语言

@profiles.where("properties @> ?", {'languages': [{'name':'German'}] }.to_json)

和多种技能(x OR y)这样的

@profiles.where("properties -> 'skills' ?| array[:skills]", skills: ['Alpha', 'Beta'])

但我需要检索多种语言查询术语德语和俄语

我该如何实现?

提前致谢

【问题讨论】:

    标签: ruby-on-rails postgresql jsonb


    【解决方案1】:

    不熟悉 JSONB,但 ActiveRecord 确实支持 and 之类的运算符

    @profiles.where("properties @> ?", {'languages': [{'name':'German'}] }.to_json).
      and(@profiles.where("properties @> ?", {'languages': [{'name':'Russian'}] }.to_json))
    

    https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-and

    【讨论】:

    • 我在提出问题之前已经考虑过这个选项,但由于没有人能够找到其他优雅的方式,我会选择你的答案。谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-04-12
    • 2013-07-10
    • 2017-07-16
    • 2015-05-20
    • 2017-11-26
    • 2018-03-20
    • 1970-01-01
    • 2020-06-11
    相关资源
    最近更新 更多