Skip to content

Instantly share code, notes, and snippets.

@lucaspiller
Last active June 26, 2021 23:03
Show Gist options
  • Save lucaspiller/615f09bb525a14163921fd56b4b8e611 to your computer and use it in GitHub Desktop.
Save lucaspiller/615f09bb525a14163921fd56b4b8e611 to your computer and use it in GitHub Desktop.
Reform 2.2 nested form (with support for cocoon gem)
= f.simple_fields_for :inputs do |input|
= render 'input_fields', f: input
.links
= link_to_add_association f, :inputs, partial: 'input_fields', force_non_association_create: true do
Add
.nested-fields
= f.input :foo, as: :string
= f.input :bar, as: :string
= f.hidden_field :_destroy
= f.hidden_field :id
= link_to_remove_association f do
Delete
class IndicatorForm < Reform::Form
InputPrepopulator = -> (options) {
if inputs.size == 0
inputs << IndicatorInput.new
end
}
InputPopulator = -> (options) {
fragment, collection, index = options[:fragment], options[:model], options[:index]
if fragment["_destroy"] == "1"
# Marked for removal
collection.delete_at(index)
return skip!
else
(item = collection[index]) ? item : collection.insert(index, IndicatorInput.new).
end
}
collection :inputs, inherit: true, prepopulator: InputPrepopulator, populator: InputPopulator do
include NestedForm
property :foo
property :bar
end
end
module NestedForm
extend ActiveSupport::Concern
included do
property :id, writeable: false
property :_destroy, virtual: true
end
def new_record?
model.new_record?
end
def marked_for_destruction?
model.marked_for_destruction?
end
end
@kvivek1115
Copy link

kvivek1115 commented May 26, 2021

This is really helpful, link_to_add_association raises undefined method reflect_on_association' for NilClass:Class`

in order to solve it

class IndicatorForm < Reform::Form
  ...
  def self.reflect_on_association(obj)
      Indicator.reflect_on_association(obj)
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment