diff --git a/lib/couchrest/model/document_queries.rb b/lib/couchrest/model/document_queries.rb index ba3ca384..5421eef8 100644 --- a/lib/couchrest/model/document_queries.rb +++ b/lib/couchrest/model/document_queries.rb @@ -58,6 +58,42 @@ def get!(id, db = database) end alias :find! :get! + # Load an array of documents from the database by an arrary of ids + # No exceptions will be raised if none of the documents were found + # + # ==== Returns + # [Object::] if the document was found + # or + # [] + # + # === Parameters + # ids:: Documents IDs + # db:: optional option to pass a custom database to use + def get_bulk(ids, db = database) + get_bulk!(ids, db) + rescue CouchRest::Model::DocumentsNotFound + [] + end + alias :find_all :get_bulk + + # Load an array of documents from the database by an arrary of ids + # An exception will be raised if none of the documents were found + # + # ==== Returns + # [Object::] if the document was found + # or + # Exception + # + # === Parameters + # ids:: Documents IDs + # db:: optional option to pass a custom database to use + def get_bulk!(ids, db = database) + docs = db.all_docs(:keys => ids, :include_docs => true) + raise CouchRest::Model::DocumentsNotFound if docs.blank? + docs["rows"].map{|row| build_from_database(row["doc"])} + end + alias :find_all! :get_bulk! + end end diff --git a/lib/couchrest/model/errors.rb b/lib/couchrest/model/errors.rb index 3633a98d..47b8be3d 100644 --- a/lib/couchrest/model/errors.rb +++ b/lib/couchrest/model/errors.rb @@ -22,6 +22,8 @@ def initialize(document) class DocumentNotFound < Errors::CouchRestModelError; end + class DocumentsNotFound < Errors::CouchRestModelError; end + class DatabaseNotDefined < Errors::CouchRestModelError def initialize(msg = nil) msg ||= "Database must be defined in model or view!" diff --git a/spec/unit/persistence_spec.rb b/spec/unit/persistence_spec.rb index 508b9699..1d7fd420 100644 --- a/spec/unit/persistence_spec.rb +++ b/spec/unit/persistence_spec.rb @@ -44,6 +44,20 @@ saved_obj.set_by_proc.should be_an_instance_of(Time) end end + + describe "bulk retrieving" do + it "should retrieve multiple documents given an array of ids" do + @obj.name = "first object" + @obj.save! + @obj_2 = WithDefaultValues.new + @obj_2.name = "second object" + @obj_2.save! + saved_objs = WithDefaultValues.find_all([@obj.id, @obj_2.id]) + saved_objs.first.name.should eq("first object") + saved_objs.last.name.should eq("second object") + saved_objs.length.should eq(2) + end + end describe "creating a model" do