I use Ruby on Rails and Postgres 9.5.
In the database I have a table called events
.
I want to find all events based on particular value in the data field.
events.data
has the following possible json value:
{ 'transition' => { 'from' => 'bacon', 'to' => 'ham' } }
How can I build a query that will find an event with data => transition => from bacon
?
Assuming that your model is called
Event
, you can do it like this:Here is jsonb operators reference.
This query will return all events where
data.transition.from
is equal tobacon
.To DRY your queries, you can add it to the repository, e.g.:
After that include it in your model:
Then you can use it like this: