Active Record: JSON Query

2020-05-03 01:02发布

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

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

Trying to query this using select:

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

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

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

Thanks for any help.

1条回答
贪生不怕死
2楼-- · 2020-05-03 01:41

This:

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

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 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.

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)

will give you the data values.

查看更多
登录 后发表回答