'how to pull all images from a hash field?
I have an Activity_Part model with a field called activity_json. this field is a hash that has a key named "image". I want to query/select only the ID of all Activity_Part only with activity_json field with key "image"
ActivityPart < ApplicationRecord {
:id => :integer,
:owner_id => :integer,
:activity_type => :string,
:activity_json => :json,
I thought of doing something like this:
x = ActivityPart.all
x.pluck(activity_json: 'image')
but I don't know how to return just the Activity ID with all the images in the activty_json field
Solution 1:[1]
I'll assume that you're using postgres.
jsonb type has the ? operator which can be used like this: ActivityPart.where("activity_json ? 'image'") as per documentation.
If your column is of a json type then consider changing it to jsonb. You can alternatively cast it to jsonb in the query like so: ActivityPart.where("activity_json::jsonb ? 'image'") but be aware that this might negatively affect the performance of the query.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kamil Gwó?d? |
