Module: MongoMapper::Plugins::Associations::NestedAttributes::InstanceMethods

Defined in:
lib/mm-nested-attrs.rb

Constant Summary collapse

UNASSIGNABLE_KEYS =
%w{ id _id _destroy }

Instance Method Summary collapse

Instance Method Details

#assign_nested_attributes_for_association(association_name, attributes_collection, allow_destroy) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/mm-nested-attrs.rb', line 26

def assign_nested_attributes_for_association(association_name, attributes_collection, allow_destroy)
	class_name = self.associations[association_name].options[:class_name] || class_name

	unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
	  raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
	end

	if attributes_collection.is_a? Hash
	  attributes_collection = attributes_collection.sort_by { |index, _| index.to_i }.map { |_, attributes| attributes }
	end

	attributes_collection.each do |attributes|
	  attributes.stringify_keys!

	  if attributes['_id'].blank?
	    send(association_name) << class_name.constantize.new(attributes)
	  elsif existing_record = send(association_name).detect { |record| record.id.to_s == attributes['_id'].to_s }
	    if existing_record.has_destroy_flag?(attributes) && allow_destroy
	      send(association_name).delete(existing_record)
	      existing_record.destroy unless class_name.constantize.embeddable?
	    else
	      existing_record.attributes = attributes.except(*UNASSIGNABLE_KEYS)
	    end
	  end
	end
end

#has_destroy_flag?(hash) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/mm-nested-attrs.rb', line 53

def has_destroy_flag?(hash)
	Boolean.to_mongo(hash['_destroy'])
end