【问题标题】:Create DSL to query postgres json similar to ActiveRecord's where创建 DSL 来查询 postgres json 类似于 ActiveRecord 的 where
【发布时间】:2016-05-20 20:01:09
【问题描述】:

在 ActiveRecord 中,我们可以为列中的属性执行where(my_attribute: value)。

这对于在 json 列中定义的属性是不可能的,而是看起来像这样:

where("document->>'my_attribute' = ?", value)

如果我们假设我的模型只有一个 json 列 document,是否可以为该列创建一个自定义可链接查询,如下所示:

dwhere(my_attribute: value)

【问题讨论】:

  • 你在 postgres 上使用过 hstore 吗?
  • 不,jsonb。 t.jsonb :document, null: false, default: '{}'
  • 搜索可以使用 hstore 的序列化字段
  • 谢谢,Rails4 已经内置了该功能。我想知道是否以及如何创建更类似于 ActiveRecord 的查询。

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


【解决方案1】:

这是我想出的最接近的:

scope :dwhere, -> (key, value) { where("document ->> '#{key}' = '?'", value) }

这样使用:

MyModel.dwhere(key, value)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    相关资源
    最近更新 更多