I have owns_count counter_cache on my items model. When i do
Items.order("owns_cache DESC")
, it returns me objects that are nil before other results. If I do
"owns_cache ASC"
, it is correct.
What should I be doing?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
How NULLs get ordered depends on the underlying database.
For PostgreSQL, you could do this:
For MySQL and SQLite:
I think MySQL sorts NULLs at the bottom of a DESC ordering though so you might not need anything special there. This COALESCE approach will also work in PostgreSQL so this would be a portable solution that should give you consistent results everywhere.
If you wanted NULLs at the bottom on an ASC sort, you’d replace the
0with something larger than the largestowns_cachenumber.