Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bartuz/74ee5834a36803d712b7 to your computer and use it in GitHub Desktop.
Save Bartuz/74ee5834a36803d712b7 to your computer and use it in GitHub Desktop.
class NestedAttributesForStrategy
def association(runner)
runner.run
end
def result(evaluation)
evaluation.object.tap do |instance|
evaluation.notify(:after_build, instance)
return attributes(instance)
end
end
private
def attributes(instance)
attrs = instance.attributes.delete_if do |k, _|
%w(id type created_at updated_at).include?(k)
end
nested_reflections(instance).each do |ref|
attrs.merge!("#{ref.name}_attributes" => instance.send(ref.name).map do |nested_obj|
attributes(nested_obj)
end)
end
attrs
end
def nested_reflections(instance)
instance._reflections.values.select do |ref|
ref.macro == :has_many && instance.respond_to?("#{ref.name}_attributes=")
end
end
end
@ccmcbeck
Copy link

Thanks for fixing. This works great in conjunction with this has_many factory pattern -- http://stackoverflow.com/a/19011173/207353

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment