Rails:带有正则表达式的 jsonb 数组列的 activerecord 查询

问题描述 投票:0回答:0

我有一个 jsonb 列作为

Product.codes
这是一组代码。下面是一些记录

id: 1,
codes: [{
  type: "ic",
  code: "SP$$DE0303$$3RPC$$$",
  loc: "MCS"
  },{
  type: "mc",
  code: "SP$$DE0303$$3..B$$$",
  loc: "MCS"}]

id: 2,
codes: [{
  type: "ic",
  code: "SP$$DE0303$$3**C$$$",
  loc: "MCS"
  }]

id: 3,
codes: [{
  type: "mc",
  code: "SP$$DE0303$$3RPB$$$",
  loc: "MCS"
  }]

我想做的是编写一个查询来查找所有记录至少包含一个具有特定类型(字符串)和代码(正则表达式)的代码,即

{code: /SP..DE0303..3..C.../, type: "ic"} 

应该退回 id 为 1 和 2 的产品。

但是

{code: /SP..DE0303..3..B.../, type: "mc"}

应该退回 id 为 2 和 3 的产品。

我已经有了用准确的字符串代码查找产品的解决方案 范围是这样的

scope :has_code, ->(code, type) { where("codes @> ?", [{code: code, type: type}].to_json) if code.present? && type.present? }

然后我可以查询

Product.has_code("SP$$DE0303$$3**C$$$", "ic")

但我直到没有成功那样的东西

scope :match_code, ->(code_exp, type) { where("....") if code_exp.present? && type.present? }

求助! 🙏

ruby-on-rails postgresql activerecord jsonb
© www.soinside.com 2019 - 2024. All rights reserved.