Question

I have a nest form that is working great. The form is basically a customer with addresses. I am trying to render a partial at both the customer and address level to indicate who created each record and who was the last person to update the record.

My view code is:

<%= form_for(@customer) do |f| %>
  <%= render 'cust_fields', f: f %>
  <%= render 'layouts/audit', audit: @customer %>
  <strong>ADDRESSES:</strong>
  <hr />
  <%= f.fields_for :addresses do |a| %>
    <%= render "address_fields", f: a %>
    <%= render 'layouts/audit', audit: :addresses %>
  <% end %>
<% end %>

The code in question is <%= render 'layouts/audit', audit: :addresses %>

This is throwing the the error:

undefined method `created_by' for :addresses:Symbol

I have tried to change :addresses to @customer.addresse but that doesn't work either. Why?

My partial code is:

<% created_user = User.find(audit.created_by) %>
<% updated_user = User.find(audit.updated_by) %>
<div class="row audit-info">
  <small>
  <div class="pull-left">
    Created by: <%= created_user.name %>
  </div>
  <div class="pull-right">
    Last updated by: <%= updated_user.name %>
  </div>
  </small>
</div>

Both the customers and addresses table have created_by and updated_by columns.

Any help would be much appreciated.

Was it helpful?

Solution

I was able to get this working by introducing the following code in my view:

<% for i in 1..@customer.addresses.size %>
    <%= f.fields_for @customer.addresses[i-1] do |a| %>
      <%= render "address_fields", f: a %>
      <%= render 'layouts/audit', audit: @customer.addresses[i-1] %>
    <% end %>
<% end %>

OTHER TIPS

Actually, the above didn't work since I was double counting the children records. What did work (after some more research) was the following:

<%= f.fields_for :addresses do |a| %>
  <div class="deleterow">
    <%= render "address_fields", f: a %>
    <%= render 'layouts/audit', audit: @customer.addresses[a.index] %>
  </div>
<% end %>

The key was using a.index, which can be seen on line 4.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top