Skip to content

Instantly share code, notes, and snippets.

@kfl62
Last active October 3, 2015 01:38
Show Gist options
  • Save kfl62/2364764 to your computer and use it in GitHub Desktop.
Save kfl62/2364764 to your computer and use it in GitHub Desktop.
HABTM relations return docs in the wrong order
class Some
include Mongoid::Document
field :some_field
has_and_belongs_to_many :habtms
def sorted_habtms
hbtm_ids.each_with_object([]){|id,a| h = habtms.find(id); a << h}
end
end
@troex
Copy link

troex commented Jul 22, 2015

Superb, Thanks! I use it this way:

def ordered_habtms
  habtm_ids.each_with_object([]) { |id, array| array << self.habtms.find(id) }
end

works great on small selections

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment