使用rails表单对象初始化编辑中的数据

时间:2017-07-12 05:05:50

标签: ruby-on-rails ruby virtus

我无法使用virtus gem初始化类属性的数据。这是我的示例代码:

class ShipmentForm
  include Virtus.mode

  attr_reader :shipment
  attr_reader :shipment_detail

  attribute :shipment_type, String
  attribute  :shipment_detail, ShipmentDetailAttribute

  def initialize(attr = {})
   if !attr['id'].nil?
    @shipment = Shipment.find(attr['id'])
    @shipment_detail = @shipment.shipment_detail
    self[:shipment_type] = attr[:shipment_type].nil? ? @shipment.shipment_type : attr[:shipment_type]
     self[:shipment_detail] = attr[:shipment_detail].nil? ? @shipment_detail.attributes : attr[:shipment_detail]
   else
    super(attr)
   end
  end
end

class ShipmentDetailAttribute
  include Virtus.model

  attribute :po_number
  attribute :job_no
  etc...
end

我的haml表格

= form_for @shipment, url: shipments_path, method: :patch do |f|
  = f.text_field :shipment_type
  = f.fields_for :shipment_detail do |detail|
    = detail.text_field :po_number
    = detail.text_field :job_no
    etc ....

shipping_detail字段(po_number,job_no)的数据未显示在文本字段内

0 个答案:

没有答案