Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby sort by (integer) "comparison of NilClass with 3200 failed"

I want to sort my records in an rails application:

@ebms = Ebm.all
@ebms.sort_by! {|u| u.number}

The u.number is defined as integer! The problem is that Rails cannot compare it with nil:

comparison of NilClass with 32400 failed

What can i do to evade this error?

like image 890
John Smith Avatar asked Aug 01 '13 08:08

John Smith


2 Answers

How about to try convert nil to integer?

   @ebms = Ebm.all
   @ebms.sort_by! { |u| u.number.to_i }
like image 97
user2641326 Avatar answered Oct 11 '22 04:10

user2641326


You can add a default value for the comparison that will be used when number is nil:

@ebms = Ebm.all
@ebms.sort_by! {|u| u.number || 0}

Or you can follow the suggestions in this answer to select those with a number and sort them, then add those without a number to the list.

like image 32
Matt Avatar answered Oct 11 '22 02:10

Matt