Forked from anonymous/nested_attributes_for_strategy.rb
Created
June 3, 2014 02:14
-
-
Save jasonm23/1a6caced83f2ea5dbae9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment