In my Rails 5 app, I'm using the Ahoy gem which uses a jsonb field (called properties
) that I don't know how to query.
A sample of the data in the properties
field:
"{\"id\":\"11\"}"
What I'm trying to do is:
- Find the records created in the last seven days (using the
time
field) - Group the records by the
id
in theproperties
field - Order the records based on which
id
had the most records
I tried this:
@foo = Ahoy::Event.where(name: "Viewed Product").where(time: 7.days.ago..Time.now).group("properties(id)").order('COUNT("properties(id)") DESC')
but I received the error, PG::UndefinedColumn: ERROR: column "properties(id)" doe not exist
I found this somewhat similar question in the issues for the gem, so I tried breaking the query into parts:
@foo = Ahoy::Event.where(name: "Viewed Product").where(time: 7.days.ago..Time.now)
@foo.group("properties REGEXP '[{,]\"id\"...).count
but then my IDE gives the error unterminated string meets the end of file
.
Can someone please help me determine what I'm doing wrong?