Module: Mongoid::Persistable::Creatable::ClassMethods

Defined in:
lib/mongoid/persistable/creatable.rb

Overview

Since:

  • 4.0.0

Instance Method Summary collapse

Instance Method Details

#create(attributes = nil, &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")

Create multiple new documents.

Person.create({ title: "Mr" }, { title: "Mrs" })

Parameters:

  • attributes (Hash, Array) (defaults to: nil)

    The attributes to create with, or an Array of multiple attributes for multiple documents.

Returns:

Since:

  • 1.0.0



143
144
145
146
147
148
149
150
151
152
153
# File 'lib/mongoid/persistable/creatable.rb', line 143

def create(attributes = nil, &block)
  _creating do
    if attributes.is_a?(::Array)
      attributes.map { |attrs| create(attrs, &block) }
    else
      doc = new(attributes, &block)
      doc.save
      doc
    end
  end
end

#create!(attributes = nil, &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")

Create multiple new documents.

Person.create!({ title: "Mr" }, { title: "Mrs" })

Parameters:

  • attributes (Hash, Array) (defaults to: nil)

    The attributes to create with, or an Array of multiple attributes for multiple documents.

  • options (Hash)

    A mass-assignment protection options. Supports :as and :without_protection

Returns:

Since:

  • 1.0.0



174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/mongoid/persistable/creatable.rb', line 174

def create!(attributes = nil, &block)
  _creating do
    if attributes.is_a?(::Array)
      attributes.map { |attrs| create!(attrs, &block) }
    else
      doc = new(attributes, &block)
      doc.fail_due_to_validation! unless doc.insert.errors.empty?
      doc.fail_due_to_callback!(:create!) if doc.new_record?
      doc
    end
  end
end