如何使用ActiveRecord仅选择存储在Postgres中的json的一部分 [英] How to select only part of json, stored in Postgres, with ActiveRecord
问题描述
说我有一个模型User
,它具有一个名为settings
的json
类型的字段.假设该字段大致如下所示:
Say I have a model User
, which has a field of type json
called settings
. Let's assume that this field looks roughly like this:
{
color: 'red',
language: 'English',
subitems:
{
item1: true,
item2: 43,
item3: ['foo', 'bar', 'baz']
}
}
如果我执行User.select(:settings)
,我将获得每个用户的所有设置.但是我只想为用户提供语言.我都尝试过:
If I do User.select(:settings)
I will get all the settings for each user. But I want to get only the languages for a user. I tried both:
User.select("settings -> 'language'")
和
User.select("settings ->> 'language'")
但这只会返回空对象:
[#<User:0x007f381fa92208 id: nil>,
...]
这有可能吗?如果是,我可以只使用json
还是要切换到jsonb
?
Is this at all possible? If yes - can I do it using just json
or do I need to switch to jsonb
?
推荐答案
尝试User.select("settings -> 'language' as user_language")
.
生成关系中的每个对象都应响应user_language
.
Try User.select("settings -> 'language' as user_language")
.
Each object in the resulting relation should respond to user_language
.
这篇关于如何使用ActiveRecord仅选择存储在Postgres中的json的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!