diff --git a/lib/nested_form/builder_mixin.rb b/lib/nested_form/builder_mixin.rb index 26a98877..fac4d0b9 100644 --- a/lib/nested_form/builder_mixin.rb +++ b/lib/nested_form/builder_mixin.rb @@ -15,6 +15,11 @@ module BuilderMixin # # <%= f.link_to_add(:tasks, :model_object => Task.new(:name => 'Task')) %> # + # If you have multiple links for adding records with different blueprints, you need to pass model_id option with a number unique for each blueprint model. + # + # <%= f.link_to_add('Add One-off Task', :tasks, :model_object => Task.new(:name => 'Task', :repeat => 'none'), :model_id => 1) %> + # <%= f.link_to_add('Add Daily Task', :tasks, :model_object => Task.new(:name => 'Task', :repeat => 'daily'), :model_id => 2) %> + # # See the README for more details on where to call this method. def link_to_add(*args, &block) options = args.extract_options!.symbolize_keys @@ -31,14 +36,14 @@ def link_to_add(*args, &block) 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) + options["data-blueprint-id"] = fields_blueprint_id = fields_blueprint_id_for_model(association, options.delete(:model_id)) args << (options.delete(:href) || "javascript:void(0)") args << options @fields ||= {} @template.after_nested_form(fields_blueprint_id) do blueprint = {:id => fields_blueprint_id, :style => 'display: none'} - block, options = @fields[fields_blueprint_id].values_at(:block, :options) + block, options = @fields[fields_blueprint_id_for(association)].values_at(:block, :options) options[:child_index] = "new_#{association}" blueprint[:"data-blueprint"] = fields_for(association, model_object, options, &block).to_str @template.content_tag(:div, nil, blueprint) @@ -108,5 +113,9 @@ def fields_blueprint_id_for(association) assocs << association assocs.join('_') + '_fields_blueprint' end + + def fields_blueprint_id_for_model(association, model_id) + fields_blueprint_id_for(association) + (model_id ? "_#{model_id}" : '') + end end end diff --git a/spec/nested_form/builder_spec.rb b/spec/nested_form/builder_spec.rb index 98456b72..60078496 100644 --- a/spec/nested_form/builder_spec.rb +++ b/spec/nested_form/builder_spec.rb @@ -175,6 +175,25 @@ output.should match(/div.+data-blueprint="#{expected}"/) end end + + context "when model_id given" do + before(:each) do + task = project.tasks.build + subject.fields_for(:tasks) { 'Task' } + subject.link_to_add('Add', :tasks, :model_id => 123) + end + + let(:output) { template.send(:after_nested_form_callbacks) } + + it "puts blueprint into data-blueprint attribute" do + expected = ERB::Util.html_escape '
Task
' + output.should match(/div.+data-blueprint="#{expected}"/) + end + + it "adds the model id to the blueprint div id" do + output.should match(/div.+id="tasks_fields_blueprint_123"/) + end + end end end end