简体   繁体   English

创建DSL以查询类似于ActiveRecord的postgres json,其中

[英]Create DSL to query postgres json similar to ActiveRecord's where

In ActiveRecord we can do where(my_attribute: value) for an attribute in a column. 在ActiveRecord中,我们可以为列中的属性执行where(my_attribute: value)

That's not possible yet with attributes defined in a json column, instead it would look like this: 对于在json列中定义的属性,这还不可能,相反,它看起来像这样:

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

If we assume that my model only has one json column, document , would it be possible to create a custom chainable query for that column looking something like this: 如果我们假设我的模型只有一个json列document ,那么可以为该列创建一个自定义可链接查询,如下所示:

dwhere(my_attribute: value)

This is the closest I've come up with: 这是我想出的最接近的:

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

To use like this: 像这样使用:

MyModel.dwhere(key, value)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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