Skip to content

Instantly share code, notes, and snippets.

@dnch
Created January 19, 2011 04:30
Show Gist options
  • Save dnch/785689 to your computer and use it in GitHub Desktop.
Save dnch/785689 to your computer and use it in GitHub Desktop.
class IncrementJumpingFormBuilder < ActionView::Helpers::FormBuilder
def fields_for_with_nested_attributes(association_name, args, block)
name = "#{object_name}[#{association_name}_attributes]"
association = args.first
if association.respond_to?(:new_record?)
association = [association] if @object.send(association_name).is_a?(Array)
elsif !association.is_a?(Array)
association = @object.send(association_name)
end
if association.is_a?(Array)
explicit_child_index = args.last[:child_index] if args.last.is_a?(Hash)
nested_child_index_start = args.last[:child_index_start] if args.last.is_a(Hash)
nested_child_index_start ||= -1
association.map do |child|
fields_for_nested_model("#{name}[#{explicit_child_index || nested_child_index(name, nested_child_index_start)}]", child, args, block)
end.join
elsif association
fields_for_nested_model(name, association, args, block)
end
end
def nested_child_index(name, nested_child_index_start)
Rails.logger.debug("Nested Child Index: #{name}, #{nested_child_index_start}")
@nested_child_index[name] ||= nested_child_index_start
@nested_child_index[name] += 1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment