Module: Mongoid::Persistence::ClassMethods

Defined in:
lib/mongoid/persistence.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#create(attributes = {}, &block) ⇒ Document

Create a new document. This will instantiate a new document and insert it in a single call. Will always return the document whether save passed or not.

Examples:

Create a new document.

Person.create(:title => "Mr")


167
168
169
# File 'lib/mongoid/persistence.rb', line 167

def create(attributes = {}, &block)
  new(attributes, &block).tap(&:save)
end

#create!(attributes = {}, &block) ⇒ Document

Create a new document. This will instantiate a new document and insert it in a single call. Will always return the document whether save passed or not, and if validation fails an error will be raise.

Examples:

Create a new document.

Person.create!(:title => "Mr")


182
183
184
185
186
# File 'lib/mongoid/persistence.rb', line 182

def create!(attributes = {}, &block)
  document = new(attributes, &block)
  fail_validate!(document) if document.insert.errors.any?
  document
end

#delete_all(conditions = {}) ⇒ Integer

Delete all documents given the supplied conditions. If no conditions are passed, the entire collection will be dropped for performance benefits. Does not fire any callbacks.

Examples:

Delete matching documents from the collection.

Person.delete_all(:conditions => { :title => "Sir" })

Delete all documents from the collection.

Person.delete_all


201
202
203
204
205
206
207
# File 'lib/mongoid/persistence.rb', line 201

def delete_all(conditions = {})
  RemoveAll.new(
    self,
    { :validate => false },
    conditions[:conditions] || {}
  ).persist
end

#destroy_all(conditions = {}) ⇒ Integer

Delete all documents given the supplied conditions. If no conditions are passed, the entire collection will be dropped for performance benefits. Fires the destroy callbacks if conditions were passed.

Examples:

Destroy matching documents from the collection.

Person.destroy_all(:conditions => { :title => "Sir" })

Destroy all documents from the collection.

Person.destroy_all


222
223
224
225
226
227
# File 'lib/mongoid/persistence.rb', line 222

def destroy_all(conditions = {})
  documents = all(conditions)
  documents.count.tap do
    documents.each { |doc| doc.destroy }
  end
end

#fail_validate!(document) ⇒ Object

Raise an error if validation failed.

Examples:

Raise the validation error.

Person.fail_validate!(person)

Raises:



235
236
237
# File 'lib/mongoid/persistence.rb', line 235

def fail_validate!(document)
  raise Errors::Validations.new(document)
end