Reputation: 4368
I have a Post
model with the column defined by the following migration:
add_column :posts, :comments, :jsonb, default: []
add_index :posts, :comments, using: :gin
I would like to know the query to run so that I have a count of all the Posts
which have the default, empty array as comments
.
Upvotes: 5
Views: 2459
Reputation: 1722
With Postgresql > 11, this is also a possible answer
Post.where('jsonb_array_length(comments) > 0')
Upvotes: 0
Reputation: 31
You can do this by converting the json to string, and count the length. Empty json will return 2. This works for both {} and []. E.g. To return non empty comment
Post.where("length(comments::text) > 2").count
Upvotes: 1