【问题标题】:Nested property fields do not show up using the Reform gem使用改革 gem 不显示嵌套属性字段
【发布时间】:2017-07-11 12:36:01
【问题描述】:

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

发货型号:

class Shipment < ApplicationRecord
  has_one :shipment_detail
end

ShipmentDetail 型号:

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 不可见。我应该怎么做才能让它们可见?

【问题讨论】:

  • collection :shipment_detail do property :po_number property :job_no end try this
  • @stef 不起作用
  • 您是否在编辑完改革类后重新启动了您的开发服务器?它可能不在重新加载路径列表中。
  • 你需要像这样实例化吗? @shipment = ShipmentForm.new(Shipment.new(:shipment_detail =&gt; ShipmentDetail.new }) 也许?
  • 是的,我重启了服务器

标签: ruby-on-rails ruby reform


【解决方案1】:

在改革中,您需要使用prepopulator 创建一个新的/空白 :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 行将在编辑表单上添加缺少的行,如果当前没有的话。

【讨论】:

  • 在编辑时不一样,嵌套属性的值没有显示
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多