9

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!

1 Answer 1

9
@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) }
Sign up to request clarification or add additional context in comments.

4 Comments

thx! But what do you think, should I change the database model to integer? I chose string because I am worried about saving numbers with are too big for integer.
@lukas...I think your data model is correct if you anticipate more than 10 digits as facebook_likes..otherwise integer is the way to go..but I think ordering by facebook_likes in the database level itself should give you the correct ordering..are you sure the ordering is not correct in case of your code?
also try the sql command(in your database terminal) select * from locations order by facebook_likes asc and analyse the result.
@lukas..you mean in your code itself, the ordering is correct?

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.