Search code examples
ruby-on-railsnested-attributes

Deeply nested form and object attributes


class Equipment has_many :equipment_maintenances and accepts_nested_attributes_for : equipment_maintenances, allow_destroy: true

class EquipmentMaintenance has_many :equipment_maintenanceitems and accepts_nested_attributes_for : equipment_maintenanceitems, allow_destroy: true

The following form can properly generate the HTML to update the grandchildren (i.e. name="equipment[equipment_maintenance_attributes][0][equipment_maintenanceitems_attributes][1][active]" as follows:

<%= form_for @equipments do |equipment| %>
  <% @equipment_maintenances.each do |equipment_maintenance| %>
    <%= equipment.fields_for :equipment_maintenance do |em| %>
      <%= em.fields_for :equipment_maintenanceitems do |f| %>
         <%= f.check_box :active %>
         <%= f.text_field :order %>
         <%# equipment_maintenanceitem.name  %>
         <%= f.select :frequenc, [3,4,6,12] %>
      <% end %>
    <% end %>
  <% end %>
  <%= equipment.submit %>
<% end %>

However, I have not found the proper syntax to reference the name of the grandchild equipment_maintenanceitem.name

Update While the original question was properly answered, the question was incompletely stated. EquipmentMaintenanceItem belongs_to :ordinary_maintenanceitem and the goal is to get equipment_maintenanceitem.ordinary_maintenanceitem.name


Solution

  • Under the original formulation of the question, the answer is:

    <%= f.object.name %>
    

    Under the updated context, the answer is:

    <%= OrdinaryMaintenanceItem('id = ?',f.object.maintenanceitem_id).pluck("name") %>
    

    not very efficient and needs to be cleaned up for array and string symbology...