Rails PostgreSQL sort by integer value of string
Asked Answered
P

1

7

I made a strategic mistake when developing database architecture on my Rails app

Now I have to implement sorting by price feature using

MyModel.order('price DESC')

price is a string type in the database, which cause 50 to be greater than 2000 for example

Are there any ways to implement such .order() without changing database structure?

EDIT:

I switched to correct type (integer) for price column. It took me an hour only to refactor.

Pacheco answered 21/10, 2016 at 15:45 Comment(4)
which rdbms are u using?Zandrazandt
Im using PostgreSQLPacheco
I think it is better to migrate column type from string to float if possible. Otherwise you should cast column: ORDER BY price::float.Turnsole
Yea Oleksandr Avoyants is right you really should just migrate the database table to have the right value. You are going to really hinder yourself if you just keep finding work arounds.Maugham
M
17

With PostgreSQL you will want to cast your string to integer/float/decimal (after you decide you 100% will not go and change the column type to correct one):

MyModel.order('price::integer DESC')

Consider this answer to make it work fast.

Meit answered 21/10, 2016 at 16:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.