ruby - Sort by doesn't sort when includes is used in rails -


i've got distance attribute in user model :

attr_accessor :distance 

so when calculate distance each user, , store in distance can sort them :

users.sort_by!(&:distance) 

and users sorted according distance appropriately. when include other associated methods i.e :

users.includes(:photo).sort_by!(&:distance) 

this doesn't sort users @ all, why this? how can sort distance include association well?

the ! in sort_by! method indicates object changed rather returns different object. when call users.includes(:photo) method returns different object. so, doing like:

users2 = users.includes(:photo) users2.sort_by!(&:distance) 

this why users object not sorted after call sort_by!. better way might be

users = users.includes(:photo).sort_by(&:distance) 

Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -