motion-prime/models/association.rb in motion-prime-0.2.0 vs motion-prime/models/association.rb in motion-prime-0.2.1

- old
+ new

@@ -16,10 +16,12 @@ # Defines bag associated with model, creates accessor for bag # # @param [String] name - the name of bag # @return [Nil] def bag(name) + klass = self + define_method(name) do |*args, &block| return _bags[name] if _bags[name] bag_key = self.info[name] if bag_key.nil? @@ -59,11 +61,10 @@ self._associations ||= {} self._associations[association_name] = options.merge(type: :one) define_method("#{association_name}=") do |value| self.send(bag_name).clear - self.send(:"#{bag_name}") << value value end define_method("#{association_name}_attributes=") do |value| self.send(bag_name).clear @@ -91,24 +92,30 @@ self._associations[association_name] = options.merge(type: :many) define_method("#{association_name}_attributes=") do |value| self.send(bag_name).clear - association = [] - value.each do |attrs| + pending_save_counter = 0 + collection = value.inject({}) do |result, attrs| model = association_name.classify.constantize.new model.fetch_with_attributes(attrs) - association << model + unique_key = model.id || "pending_#{pending_save_counter+=1}" + result.merge(unique_key => model) end - self.send(:"#{bag_name}=", association) - association + association_data = collection.values + self.send(:"#{bag_name}=", association_data) + association_data end define_method("#{association_name}=") do |value| self.send(bag_name).clear self.send(:"#{bag_name}=", value) end - define_method("#{association_name}") do - self.send(:"#{bag_name}").to_a + define_method("#{association_name}") do |options = {}| + bag = self.send(:"#{bag_name}") + collection_options = { + association_name: association_name + } + AssociationCollection.new(bag, collection_options, options) end end end end \ No newline at end of file