Skip to content
This repository was archived by the owner on Dec 12, 2021. It is now read-only.

Datamapper compatibility #194

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 21 additions & 8 deletions lib/nested_form/builder_mixin.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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