29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
# File 'lib/dry_forms/builder_additions.rb', line 29
def fields_for_association association, *args, &block
options = args.
association = association.to_s
objects = args.first ? [*args.first] : @object.send(association)
html = options.delete(:html)
unless @object.respond_to? "#{association.pluralize}_attributes="
raise NotImplementedError, "Please call `accepts_nested_attributes_for :#{association.pluralize}` in your `#{@object.class}` Model"
end
raise ArgumentError, "Missing block" unless block_given?
association_class = @object.class.reflect_on_association(association.to_sym).klass
singular_name = association.singularize
fields = objects.map{ |obj| association_fields(association, obj, :html => html, &block) }.join
new_object = @object.send(association).build options.delete(:default_attributes) || {}
js_fields = association_fields association, new_object, :child_index => "new_#{singular_name}", :html => html, &block
association_fields = " <div id=\"\#{association}\">\n \#{fields}\n \#{@template.javascript_tag \"var fields_for_\#{singular_name} = '\#{js_fields.strip.gsub /\\n\\s+|\\n/, ''}';\"}\n <a href=\"#\" class=\"add_fields\" data-association=\"\#{singular_name}\">\#{I18n.t 'add', :model => association_class.human_name}</a>\n </div>\n HTML\n\n @template.concat ActiveSupport::SafeBuffer.new association_fields\nend\n"
|