Module: DryForms::BuilderAdditions

Defined in:
lib/dry_forms/builder_additions.rb

Instance Method Summary collapse

Instance Method Details

#custom_fields_for(*args, &block) ⇒ Object



58
59
60
61
62
63
# File 'lib/dry_forms/builder_additions.rb', line 58

def custom_fields_for *args, &block
  opts      = args.extract_options!
  html_opts = opts.delete(:html) || {}
  fields    = @template.capture{fields_for *(args << opts), &block}
  @template.concat ActiveSupport::SafeBuffer.new DryForms.fields_for_markup(fields, html_opts) unless fields.empty?
end

#fields_for_association(association, *args, &block) ⇒ Object

Raises:

  • (ArgumentError)


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.extract_options!
  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 = <<-HTML
  <div id="#{association}">
    #{fields}
    #{@template.javascript_tag "var fields_for_#{singular_name} = '#{js_fields.strip.gsub /\n\s+|\n/, ''}';"}
    <a href="#" class="add_fields" data-association="#{singular_name}">#{I18n.t 'add', :model => association_class.human_name}</a>
  </div>
  HTML

  @template.concat ActiveSupport::SafeBuffer.new association_fields
end