Last active
June 26, 2021 23:03
-
-
Save lucaspiller/615f09bb525a14163921fd56b4b8e611 to your computer and use it in GitHub Desktop.
Reform 2.2 nested form (with support for cocoon gem)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
= 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is really helpful,
link_to_add_association
raisesundefined method
reflect_on_association' for NilClass:Class`in order to solve it