Method: DataMapper::Adapters::DataObjectsAdapter#create

Defined in:
lib/dm-core/adapters/data_objects_adapter.rb

#create(resources) ⇒ Integer

For each model instance in resources, issues an SQL INSERT (or equivalent) statement to create a new record in the data store for the instance

Note that this method does not update identity map. A plugin needs to use adapter directly, it is up to plugin developer to keep identity map up to date.

Parameters:

  • resources (Enumerable(Resource))

    The list of resources (model instances) to create

Returns:

  • (Integer)

    The number of records that were actually saved into the database



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/dm-core/adapters/data_objects_adapter.rb', line 30

def create(resources)
  resources.each do |resource|
    model      = resource.model
    serial     = model.serial(name)
    attributes = resource.dirty_attributes

    properties  = []
    bind_values = []

    # make the order of the properties consistent
    model.properties(name).each do |property|
      next unless attributes.key?(property)

      bind_value = attributes[property]

      # skip insering NULL for columns that are serial or without a default
      next if bind_value.nil? && (property.serial? || !property.default?)

      # if serial is being set explicitly, do not set it again
      if property.equal?(serial)
        serial = nil
      end

      properties  << property
      bind_values << bind_value
    end

    statement = insert_statement(model, properties, serial)
    result    = execute(statement, *bind_values)

    if result.to_i == 1 && serial
      serial.set!(resource, result.insert_id)
    end
  end
end