深度嵌套的表单和对象属性

时间:2017-01-11 22:23:02

标签: ruby-on-rails nested-attributes

类设备has_many :equipment_maintenancesaccepts_nested_attributes_for : equipment_maintenances, allow_destroy: true

类设备维护has_many :equipment_maintenanceitemsaccepts_nested_attributes_for : equipment_maintenanceitems, allow_destroy: true

以下表单可以正确生成HTML以更新孙子(即name="equipment[equipment_maintenance_attributes][0][equipment_maintenanceitems_attributes][1][active]",如下所示:

<%= 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 %>

但是,我没有找到适当的语法来引用孙equipment_maintenanceitem.name

的名称

更新在原始问题得到妥善回答的同时,问题未得到充分说明。 EquipmentMaintenanceItem belongs_to :ordinary_maintenanceitem,目标是获得equipment_maintenanceitem.ordinary_maintenanceitem.name

2 个答案:

答案 0 :(得分:0)

<%= 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 %>
         <%= f.label :name  %>
         <%= f.select :frequenc, [3,4,6,12] %>
      <% end %>
    <% end %>
  <% end %>
  <%= equipment.submit %>
<% end %>

一种简单的方法是使用label来显示equipment_maintenanceitems的名称

答案 1 :(得分:0)

根据问题的原始表述,答案是:

<%= f.object.name %>

在更新的背景下,答案是:

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

效率不高,需要清理数组和字符串符号...