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.

4
  • which rdbms are u using? Commented Oct 21, 2016 at 15:46
  • Im using PostgreSQL Commented Oct 21, 2016 at 15:48
  • 2
    I think it is better to migrate column type from string to float if possible. Otherwise you should cast column: ORDER BY price::float. Commented Oct 21, 2016 at 15:49
  • 2
    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. Commented Oct 21, 2016 at 15:54

1 Answer 1

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.

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

Comments

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.