nested_form_fields
nested_form_fields copied to clipboard
nested_form.object.parent.attribute doesn't work for some parents
In the code below, ff.object.product.name works but ff.object.sales_order_item and ff.object.delivery doesn't. They all have the same associations in the model. belongs to and has_many, optional: true.
If I change to form.fields_for, all the values are displayed. Is there something going on under the hood that disables getting object.parent.attribute for some parents?
<%= form.nested_fields_for :delivery_items, wrapper_tag: :tr do |ff| %>
<td class="col-md-1">
<div class="input-product_code-div">
<%= ff.object.product.name %> <br>
<%= ff.object.sales_order_item.address %> <br>
<%= ff.object.delivery.id %>
<%end%>
</div>
</td>
<% end %>
That is odd. Is the main form object already saved in the db? Curious, can you try ff.object.reload.sales_order_item? Does that work? Seems ff.object is not initialized properly.
I tried your suggestion, it still doesn't work but now produces a different error: Couldn't find DeliveryItem without an ID
My current workaround is to simply use rails' standard fields_for
and everything works as expected.
Ah, so ff.object.reload.delivery
produces this? Is delivery
a belongs_to association? If so what does ff.object.delivery_id
return?
delivery items
belongs_to delivery
.
delivery
has_many delivery_items
.
ff.object.delivery_id
outputs the integer that connects delivery_items
to delivery
.
Okay, so ff.object.delivery
returns nil, even though the id is in ff.object.delivery_id
. The easy workaround then is to do delivery = Delivery.find ff.object.delivery_id
. What is the object of the main form
? Can you post the whole form here?
The main form object is @delivery
. I tried doing the "find" workaround but that doesnt work, it suddenly doesn't detect the delivery_id anymore. Here is the whole form, where I used form_for instead, this works:
<%= form_with(model: delivery, local: true) do |form| %> <% if delivery.errors.any? %>
<%= pluralize(delivery.errors.count, "error") %> prohibited this delivery from being saved:
<ul>
<% delivery.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
Thanks. You use the new form_with
, not form_for
. Does your form also work with form_for? And did you try that with nested_form_fields?
Oh, and if the whole form is for delivery, there is no need to get the delivery inside the nested_form_fields - you have it already.
I tried changing to form_for
for delivery
form and fields_for
for delivery_items
form. They work, but the moment I change delivery_items
to nested_fields_for
, it fails with the same error
Okay, so only issue really is ff.object.sales_order_item
that could be grabbed by doing:
sales_order_item = SalesOrderItem.find ff.object.sales_order_item_id if ff.object.sales_order_item_id
Easy workaround, but I understand it still is a workaround. Need to dig deeper into the code to find out what is going on.