NoMethodError for the nil object on sort_by and all objects exist

So, I have a bunch of users, everyone has user.dj_name attributes. This is a confirmed need for a model, but I'm still careful here because I have problems.

I want to get a bunch of users, and then order them by their dj_name. Something like that:

@djs = Event.all.map { |e| e.program.user }.sort_by {|x,y| x.dj_name <=> y.dj_name } 

where he pulls all the DJs who have events (shows). It does not work with NoMethodError: undefined `dj_name 'method for nil: NilClass

So I tried:

 @djs = Event.all.map { |e| e.program.user } @djs.compact.sort_by! {|x,y| x.dj_name <=> y.dj_name rescue nil} 

And it does not sort. Without the "rescue nil" clause, I get the same error.

And if I make a refusal! if the object is zero, I get nothing.

 > @djs.reject! {|d| d.nil? } => nil 

It seems that none of the objects in the array is equal to zero, the sorting mechanism gives me errors, and saving it just stops the sorting process and returns an immutable array.

halp?

+4
source share
2 answers

Use database sorting for this task. You can renew your requests using:

 Event.all(:include => {:program => :user}, :order => 'users.dj_name') 

Decoupling this query will cause the include method to make association associations in your models and order create ORDER BY in your query.

+2
source

Use sort! , not sort_by! .

sort_by! passes one argument to its block. So when you call .sort_by! {|x,y| ... } .sort_by! {|x,y| ... } .sort_by! {|x,y| ... } , y always nil .

The purpose of sort_by! - sort by keys instead of elements. The block receives one element and must return the key of the element that will be used for sorting.

In this code:

 @djs.compact.sort_by! {|x,y| x.dj_name <=> y.dj_name rescue nil} 

the block returns nil as the key for each element. As a result, sorting does not occur.

By the way, I agree with @MurifoX that in this particular case you should sort by database.

+2
source

Source: https://habr.com/ru/post/1484932/


All Articles