4

I'm trying to order by a jsonb column in rails using:

Stat.order("data ->'likes'->'followed_by' ASC")

I keep getting this error returned.

PG::UndefinedFunction: ERROR:  could not identify an ordering operator for type json

I can't figure out is it my formatting? The followed_by attribute is a int.

Thank you!

0

1 Answer 1

12

I'm not certain but according to http://www.postgresql.org/docs/9.3/static/functions-json.html

  1. -> "Get JSON object field"
  2. ->> "Get JSON object field as text"

So perhaps activerecord can't sort the field but can sort the text?

Try: Stat.order("data ->'likes'->>'followed_by' ASC")

1
  • For others finding this; I needed to sort by a date in a jsonb field. Using "my_column ->'date' DESC" returned a text object. This worked because by date format is "YYYY-MM-DD". But I used the object notation and it worked as an actual date: "my_column ->>'date' DESC"
    – Beartech
    Commented Jul 8, 2019 at 3:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.