module ActiveTriples::NestedAttributes
Constants
- UNASSIGNABLE_KEYS
Private Instance Methods
assign_nested_attributes_for_collection_association(association_name, attributes_collection)
click to toggle source
@param [Symbol] association_name @param [Hash, Array] attributes_collection @example
assign_nested_attributes_for_collection_association(:people, { '1' => { id: '1', name: 'Peter' }, '2' => { name: 'John' }, '3' => { id: '2', _destroy: true } })
Will update the name of the Person with ID 1, build a new associated person with the name 'John', and mark the associated Person with ID 2 for destruction.
Also accepts an Array of attribute hashes:
assign_nested_attributes_for_collection_association(:people, [ { id: '1', name: 'Peter' }, { name: 'John' }, { id: '2', _destroy: true } ])
# File lib/active_triples/nested_attributes.rb, line 40 def assign_nested_attributes_for_collection_association(association_name, attributes_collection) options = self.nested_attributes_options[association_name] # TODO #check_record_limit!(options[:limit], attributes_collection) attributes_collection = attributes_collection.values if attributes_collection.is_a?(Hash) association = self.send(association_name) attributes_collection.each do |attributes| attributes = attributes.with_indifferent_access if !call_reject_if(association_name, attributes) if attributes['id'] && existing_record = association.detect { |record| record.rdf_subject.to_s == attributes['id'].to_s } assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy]) else association.build(attributes.except(*UNASSIGNABLE_KEYS)) end end end end
assign_to_or_mark_for_destruction(record, attributes, allow_destroy)
click to toggle source
Updates a record with the attributes
or marks it for destruction if allow_destroy
is true
and has_destroy_flag? returns true
.
# File lib/active_triples/nested_attributes.rb, line 68 def assign_to_or_mark_for_destruction(record, attributes, allow_destroy) record.attributes = attributes.except(*UNASSIGNABLE_KEYS) record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy end
call_reject_if(association_name, attributes)
click to toggle source
# File lib/active_triples/nested_attributes.rb, line 75 def call_reject_if(association_name, attributes) return false if has_destroy_flag?(attributes) case callback = self.nested_attributes_options[association_name][:reject_if] when Symbol method(callback).arity == 0 ? send(callback) : send(callback, attributes) when Proc callback.call(attributes) end end
has_destroy_flag?(hash)
click to toggle source
Determines if a hash contains a truthy _destroy key.
# File lib/active_triples/nested_attributes.rb, line 86 def has_destroy_flag?(hash) ["1", "true"].include?(hash['_destroy'].to_s) end