Rails PostgreSQL sort by integer value of string
activerecord, postgresql, ruby-on-rails, ruby-on-rails-4, ruby-on-rails-5
Solution
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.
Problem
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.