活动记录:JSON查询 [英] Active Record: JSON Query

查看:62
本文介绍了活动记录:JSON查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库模型中,我有一个具有以下结构的json字段:

Inside my database model, I've got a json field which has the following structure:

json_field: {"data"=>{"key_1"=>"value1", "key_2"=>"value"} }

尝试使用select查询此内容:

Trying to query this using select:

Model.select(:id, "json_field -> 'data'")
Model.select(:id, "json_field -> 'data' as data")

产生对象数组,但未选择json字段。

yields the array of objects, but without the json field selected.

#<ActiveRecord::Relation [#<Model id: 1, Model id: 2 ...>]

感谢任何

推荐答案

此:

#<ActiveRecord::Relation [#<Model id: 1, Model id: 2 ...>]

是在查询上调用 inspect 的结果,而 inspect 只会显示模型知道这一点。该模型将在启动过程中查询表中的列,以便仅了解表中实际存在的列。

is the result of calling inspect on the query and inspect will only display columns that the model knows about it. The model will query the table for the columns during startup so it will only know about columns that are actually in the table.

ActiveRecord使用<动态创建列访问器方法code> method_missing ,因此它可以在查询中创建方法表中的内容,而不是实际表中的列。

ActiveRecord creates column accessor methods on the fly using method_missing so it can create methods things in a query that aren't columns in the actual table.

所以您的 data 在那里,您只需要按名称要求即可,例如:

So your data is there, you just have to ask for it by name, for example:

Model.select(:id, "json_field -> 'data' as data").map(&:data)

将为您提供数据值。

这篇关于活动记录:JSON查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆