Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort string containing numbers in ruby/rails

I want to sort all my locations depending on how many facebook likes they have. But facebook_likes is not an integer, it is a string.

This is the rails code I use: @locations = Location.order("facebook_likes ASC").all

Right now I get something like this:

  • 10
  • 100
  • 201
  • 2
  • 304
  • 400000
  • 50
  • ...

How can I sort depending on the value, so that the location with the most checkins is on the top. Is this solution with using strings instead of integers flawed form the beginning?

thx for your help!

like image 514
Lukas Hoffmann Avatar asked Jun 08 '11 10:06

Lukas Hoffmann


1 Answers

@locations = Location.all.sort { |a, b| b.facebook_likes.to_i <=> a.facebook_likes.to_i }

or

@locations = Location.all.sort_by { |a| -(a.facebook_likes.to_i) }
like image 66
rubyprince Avatar answered Nov 05 '22 23:11

rubyprince