simple_fields_for takes a second argument the object: https://github.com/plataformatec/simple_form/blob/master/lib/simple_form/action_view_extensions/form_helper.rb#L33 maybe if you pass your existing submitter it will work.
Creating a nested object/modal from an existing nested object/modal in Ruby on Rails
-
05-03-2022 - |
Question
I am using deeply nested model in my project (using simple_form and cocoon). Everything works fine as long as all nested objects are new.
My problem is, that I want to create a nested object from an existing (nested) object.
Here is my model
class Application < ActiveRecord::Base
belongs_to :submitter
has_one :composition
accepts_nested_attributes_for :submitter, :composition
end
class Submitter < ActiveRecord::Base
has_one :spouse
has_many :children
has_many :receipts
has_many :applications
accepts_nested_attributes_for :spouse, :children, :receipts, :applications
end
class Child < ActiveRecord::Base
belongs_to :submitter
has_many :receipts
end
The working process looks like this:
new Application --> new Submitter --> new Child
All can be created using one form.
Additionally, I also want to implement the following process:
new Application --> existing Submitter --> new Child
The existing object should be chosen by a dropdown list box.
Here is the (simplified, working) code of the view:
new.html.erb
<%= simple_form_for(@application) do |f| %>
<%= f.simple_fields_for :submitter do |submitter| %>
<%= render "submitter_fields", :f => submitter %>
<% end %>
<% end %>
_submitter_fields.html.erb
<%= f.input :firstname %>
<%= f.input :lastname %>
<%= render "child", :f => f %>
_child.html.erb
<div id="childs">
<%= f.simple_fields_for :children do |child| %>
<%= render "child_fields", :f => child %>
<% end %>
<div class="links">
<%= link_to_add_association 'Add child', f, :children %>
</div>
</div>
_child_fields.html.erb
<div class="nested-fields">
<%= f.input :firstname %>
<%= f.input :lastname %>
<%= link_to_remove_association "Remove child", f %>
</div>
Now I want to add a dropdown list which is populated with all existing Submitters. For example:
<%= f.assosciation :submitter %>
And here starts my problem: To build the form for adding a new child to the selected submitter, I need to assign this object to the form builder. I have no idea how to do this.
Can somebody give me a hint how to implement this? Or is this scenario simply not possible?
Thanks in advance!
Christian
Solution