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")

Sign up to request clarification or add additional context in comments.

1 Comment

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"

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.