Skip to content
This repository was archived by the owner on Jun 9, 2022. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions lib/mongoid/sorted_relations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,17 @@ def self.included(base)

def freeze_relation_ids
@cache_sorted_documents = {}
@cache_sorted_ids = {}

self.relations.each do |k,v|
if [:references_many, :references_and_referenced_in_many].include? v.macro
@cache_sorted_ids[v.key] = [self.send(v.key)].flatten.map{ |rid| rid.to_s }
self.class.send(:define_method, "sorted_#{v.name}") { sorted_relation v }
end
end
end

def sorted_relation(relation)
if not @cache_sorted_documents[relation.name]
documents = self.send(relation.name).sort_by { |x| @cache_sorted_ids[relation.key].index(x.id.to_s) }
documents = self.send(relation.name).sort_by { |x| self.send(relation.key).index(x.id) }
@cache_sorted_documents[relation.name] = Mongoid::FakeCriteria.new(documents)
end

Expand Down
15 changes: 15 additions & 0 deletions spec/mongoid/sorted_relations_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,21 @@
before { book.save and book.reload }

the("book.sorted_authors.map(&:name)") { should eql ['Sun Tzu', 'Sun Wu', 'Lao Zi'] }

end
end

context "modifying a loaded model" do
let (:book) {Book.new(:title => 'The Art of War')}

it "enables sorting on a preloaded model" do
author1 = Author.create(:name => 'auth1')
author2 = Author.create(:name => 'auth2')
book.authors << author2
book.authors << author1
book.sorted_authors.map(&:name).should eql ['auth2', 'auth1']
end

end

end