简体   繁体   中英

Rails - Querying a JSON Field

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:

  1. Find the records created in the last seven days (using the time field)
  2. Group the records by the id in the properties field
  3. 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?

如果你正在使用PostgreSQL,我相信你必须像这样引用json列: .group("properties ->> 'id'")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM