# File lib/spyke/associations/has_many.rb, line 45 def primary_keys_present_in_existing? embedded_attributes && embedded_attributes.any? { |attr| attr.has_key?(primary_key) } end
class Spyke::Associations::HasMany
Public Class Methods
new(*args)
click to toggle source
Calls superclass method
Spyke::Associations::Association::new
# File lib/spyke/associations/has_many.rb, line 4 def initialize(*args) super @options.reverse_merge!(uri: "#{parent_path}/:#{foreign_key}/#{@name}/(:#{primary_key})") @params[foreign_key] = parent.id end
Public Instance Methods
assign_nested_attributes(incoming)
click to toggle source
# File lib/spyke/associations/has_many.rb, line 14 def assign_nested_attributes(incoming) incoming = incoming.values if incoming.is_a?(Hash) combined_attributes = combine_with_existing(incoming) clear_existing! combined_attributes.each do |attributes| build(attributes) end end
load()
click to toggle source
# File lib/spyke/associations/has_many.rb, line 10 def load self end
Private Instance Methods
add_to_parent(record)
click to toggle source
# File lib/spyke/associations/has_many.rb, line 57 def add_to_parent(record) parent.attributes[name] ||= [] parent.attributes[name] << record record end
clear_existing!()
click to toggle source
# File lib/spyke/associations/has_many.rb, line 49 def clear_existing! update_parent [] end
combine_with_existing(incoming)
click to toggle source
# File lib/spyke/associations/has_many.rb, line 29 def combine_with_existing(incoming) return incoming unless primary_keys_present_in_existing? combined = embedded_attributes + incoming group_by_primary_key(combined).flat_map do |primary_key, hashes| if primary_key.present? hashes.reduce(:merge) else hashes end end end
embedded_attributes()
click to toggle source
# File lib/spyke/associations/has_many.rb, line 53 def embedded_attributes @embedded_attributes ||= parent.attributes.to_params[name] end
group_by_primary_key(array)
click to toggle source
# File lib/spyke/associations/has_many.rb, line 41 def group_by_primary_key(array) array.group_by { |h| h.with_indifferent_access[primary_key].to_s } end
parent_path()
click to toggle source
# File lib/spyke/associations/has_many.rb, line 25 def parent_path parent.class.model_name.element.pluralize end
primary_keys_present_in_existing?()
click to toggle source