Created
May 10, 2009 22:21
-
-
Save Odaeus/109772 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
# Rails Monkey Patch for fields_for with nested attributes. | |
# Allows an array to be supplied to a nested fields_for call instead | |
# of just a single object. | |
module ActionView | |
module Helpers | |
class FormBuilder | |
def fields_for_with_nested_attributes(association_name, args, block) | |
name = "#{object_name}[#{association_name}_attributes]" | |
obj_arg = args.first | |
if obj_arg.respond_to?(:new_record?) | |
if @object.send(association_name).is_a?(Array) | |
records = [obj_arg] | |
else | |
records = obj_arg | |
end | |
elsif obj_arg.is_a?(Array) && obj_arg.first.respond_to?(:new_record?) | |
records = obj_arg | |
else | |
records = @object.send(association_name) | |
end | |
if records.is_a?(Array) | |
explicit_child_index = args.last[:child_index] if args.last.is_a?(Hash) | |
records.map do |child| | |
fields_for_nested_model("#{name}[#{explicit_child_index || nested_child_index}]", child, args, block) | |
end.join | |
else | |
fields_for_nested_model(name, records, args, block) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment