创建DSL以查询postgres json,类似于ActiveRecord的位置

时间:2016-05-20 20:01:09

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

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

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

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

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

dwhere(my_attribute: value)

1 个答案:

答案 0 :(得分:1)

这是我最接近的:

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

要像这样使用:

MyModel.dwhere(key, value)