Skip to content

Instantly share code, notes, and snippets.

@sineed
Created February 28, 2014 08:29
Show Gist options
  • Save sineed/9267389 to your computer and use it in GitHub Desktop.
Save sineed/9267389 to your computer and use it in GitHub Desktop.
FactoryGirl.nested_attributes_for(your_ar_factory_with_nested_attributes)
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
@Bartuz
Copy link

Bartuz commented Aug 27, 2014

I'm having undefined methodreflections'`

@francirp
Copy link

francirp commented Mar 6, 2015

Where do you put this file?

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