diff --git a/lib/nested_form/builder_mixin.rb b/lib/nested_form/builder_mixin.rb index 18e82a04..4350675b 100644 --- a/lib/nested_form/builder_mixin.rb +++ b/lib/nested_form/builder_mixin.rb @@ -14,12 +14,6 @@ module BuilderMixin def link_to_add(*args, &block) options = args.extract_options!.symbolize_keys association = args.pop - - unless (reflection = object.class.reflect_on_association(association)) - raise ArgumentError, "Failed to find #{object.class.name} association by name \"#{association}\"" - end - model_object = reflection.klass.new - options[:class] = [options[:class], "add_nested_fields"].compact.join(" ") options["data-association"] = association options["data-blueprint-id"] = fields_blueprint_id = fields_blueprint_id_for(association) @@ -28,7 +22,7 @@ def link_to_add(*args, &block) @fields ||= {} @template.after_nested_form(fields_blueprint_id) do - blueprint = fields_for(association, model_object, :child_index => "new_#{association}", &@fields[fields_blueprint_id]) + blueprint = fields_for(association, model_object(association), :child_index => "new_#{association}", &@fields[fields_blueprint_id]) blueprint_options = {:id => fields_blueprint_id, :style => 'display: none'} @template.content_tag(:div, blueprint, blueprint_options) end @@ -57,7 +51,7 @@ def link_to_remove(*args, &block) args << (options.delete(:href) || "javascript:void(0)") args << options - (hidden_field(:_destroy) << @template.link_to(*args, &block)).html_safe + (hidden_field(:_delete, :value => 0) << @template.link_to(*args, &block)).html_safe end def fields_for_with_nested_attributes(association_name, *args) @@ -79,5 +73,24 @@ def fields_blueprint_id_for(association) assocs << association assocs.join('_') + '_fields_blueprint' end + + ## + # Instanciate a new object of association + # + def model_object(association) + if object.class.respond_to?(:reflect_on_association) + unless (reflection = object.class.reflect_on_association(association)) + raise ArgumentError, "Failed to find #{object.class.name} association by name \"#{association}\"" + end + reflection.klass.new + else + unless (reflection = object.class.relationships[association]) + raise ArgumentError, "Failed to find #{object.class.name} association by name \"#{association}\"" + end + reflection.target_model.new + + end + + end end end