Active Record: JSON Query

后端 未结 1 1257
孤独总比滥情好
孤独总比滥情好 2021-01-28 14:18

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

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


        
相关标签:
1条回答
  • 2021-01-28 14:30

    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.

    0 讨论(0)
提交回复
热议问题