Question: Return element of jsonb field with activerecord select

Question

Return element of jsonb field with activerecord select

Answers 2
Added at 2017-01-02 21:01
Tags
Question

How do I 'select' a value from within a jsonb stored field?

e.g.

@model1:
data: {"special_date" => "Wed, 16 Mar 2016 11:20:20 -0700", ....}
@model2:
data: {"special_date" => "Wed, 23 Mar 2016 11:20:20 -0700", ....}

I want something like

Model.all.select("data -> 'special_date'")
Answers to

Return element of jsonb field with activerecord select

nr: #1 dodano: 2017-01-02 21:01

This isn't perfect since it uses pluck rather than select, but

Model.pluck("data -> 'special_date'")

or if you need more than one column

Model.pluck(:id, "data -> 'special_date'")

works.

nr: #2 dodano: 2017-01-02 21:01

Assuming you want to fetch the entire record as well as a particular piece of data from within the jsonb column, you can chain on select:

model = Model.select('*').select("data -> 'special_date' as special_date").first
model.special_date #=> "Wed, 23 Mar 2016 11:20:20 -0700"
Source Show
◀ Wstecz