Reputation: 1106
I have a Review
model, which contains a field, answer
. answer
is a simple hash. Edit: answer
is stored as a jsonb
in the database.
create_table "reviews", force: :cascade do |t|
t.jsonb "answer", default: {}
end
The Review
model's fields are as follows:
id: 1,
venue_id: 1,
answer:
{
"loved_subject": "atmosphere",
"hated_subject": "service"
},
...
I want to grab all Reviews where the answer[:loved_subject]
is equal to "atmosphere"
So far I've tried variations on the below:
Review.where(answer: { loved_subject: "atmosphere" })
It doesn't error out, but it only returns an empty array. I know 100% for a fact that there do exist entries where loved_subject
is indeed "atmosphere"
, so obviously my query is being written out incorrectly.
How would I go about writing out this query?
Upvotes: 1
Views: 1244
Reputation: 6255
Since answer
is a jsonb
as specified in the edit, you can use jsonb queries:
Review.where("answer->>'loved_subject' = ?", 'atmosphere')
Upvotes: 1