Fellow Stranger
Fellow Stranger

Reputation: 34013

Order by number in Postgres JSONB column

I have a position key defined in my JSONB column.

The values are treated as text, so the following query

MyModel.order("data ->> 'position' ASC").each {|x| puts x.position}

returns:

0
1
10
2
3

How can I treat position as integer and order my model based on that?

Upvotes: 1

Views: 1824

Answers (1)

David Aldridge
David Aldridge

Reputation: 52336

Purely a guess, but maybe:

MyModel.order("(data ->> 'position')::Integer ASC").each {|x| puts x.position}

Upvotes: 5

Related Questions