3

我正在使用改革 gem 在我当前的项目中创建一个表单对象,但嵌套字段没有显示在表单中。这是我的代码:

出货型号:

class Shipment < ApplicationRecord
  has_one :shipment_detail
end

出货详细型号:

class ShipmentDetail < ApplicationRecord
  belongs_to :shipment
end

改革班

class ShipmentForm < Reform::Form
  property :shipment_type
  property :measure

  property :shipment_detail do
    property :po_number
    property :job_no
  end
end

控制器

class ShipmentsController < ApplicationController
  def new
    @shipment = ShipmentForm.new(Shipment.new)
  end
end

模板

<%= form_for @shipment, url: shipments_path, method: :post do |f| %>
  <%= f.label :shipment_type %><br />
  <%= f.text_field :shipment_type %><br /><br />

  <%= f.label :measure %><br />
  <%= f.text_field :measure %><br /><br />

  <%= f.fields_for :shipment_detail do |d| %>
    <%= d.label :po_number %><br />
    <%= d.text_field :po_number %><br /><br />

    <%= d.label :job_no %>
    <%= d.text_field :job_no %><br /><br />
  <% end %>
<% end %>

只有字段shipment_typemeasure在表单上可见,po_numberjob_no不是。我应该怎么做才能使它们可见?

4

1 回答 1

2

在改革中,您需要使用 aprepopulator创建一个新的/空白的 :shipment_detail 部分以显示在表单上。

http://trailblazer.to/gems/reform/prepopulator.html

  • prepopulators 是当您想要在渲染之前填写字段(又名默认值)或添加嵌套表单时。
  • populators 是在验证之前运行的代码。

这是我在代码中使用的内容,您可以从中获得想法:

   collection :side_panels, form: SidePanelForm,
    prepopulator: ->(options) {
      if side_panels.count == 0
        self.side_panels << SidePanel.new(sales_order_id: sales_order_id, collection: sales_order.collection)
      end
    }
  • 必须手动调用预填充。

     Controller#new
    @shipment_form = ShipmentForm.new(Shipment.new)
    
    @shipment_form.shipment_detail #=> nil
    
    @shipment_form.prepopulate!
    
    @shipment_form.shipment_detail #=> <nested ShipmentDetailForm @model=<ShipmentDetail ..>>
    

RE: 编辑表格

如果您在新操作中创建 ShipmentForm 并将详细信息部分留空,稍后您希望这些字段出现在编辑操作中,您还需要在该操作上再次运行预填充器。就像新动作一样。

在我上面的代码中,if side_panels.count == 0如果当前没有,我将在编辑表单上添加缺少的行。

于 2017-07-11T13:00:21.867 回答