首页 > 解决方案 > 如何创建和提交一个嵌套表单,其中的值通过关联从 has_many 填充?

问题描述

我想创建一个winnow_batch有很多bean_shipments通过bean_winnow_batches.

 create_table "bean_shipments", force: :cascade do |t|
    t.string "lotcode", null: false
    t.decimal "weight_remaining_kg"
  end

  create_table "bean_winnow_batches", force: :cascade do |t|
    t.integer "bean_shipment_id"
    t.integer "winnow_batch_id"
    t.decimal "bean_shipment_weight_used_kg"
end

class BeanShipment < ApplicationRecord
  has_many :bean_winnow_batches
  has_many :winnow_batches, through: :bean_winnow_batches
  accepts_nested_attributes_for :bean_winnow_batches
end

class WinnowBatch < ApplicationRecord
  has_many :bean_winnow_batches
  has_many :bean_shipments, through: :bean_winnow_batches
  accepts_nested_attributes_for :bean_winnow_batches
end

class BeanWinnowBatch < ApplicationRecord
  belongs_to :bean_shipment
  belongs_to :winnow_batch
end

winnow_batch\new视图上,我想展示所有bean_shipments具有bean_shipment.weight_remaining_kg < 0.

用户应该能够通过输入使用的重量来添加bean_shipments多个winnow_batch

我的观点应该是这样的:

<%= form_with(model: winnow_batch, local: true) do |form| %>
  <%= form.fields_for :bean_winnow_batches do |bwb| %>
     <table class="table1">
        <tr><th>Raw Beans in Inventory</th></tr>
        <tr>
          <td><i>Lot</td>
          <td><i>Weight in Iventory (kg)</td>
          <td><i>Weight Used in Winnow Batch (kg)</td>
        </tr>
        <tr>  
          <td><%= bwb.bean_shipment.lotcode %></td>
          <td><%= bwb.bean_shipment.weight_remaining_kg %></td>
          <td><%= bwb.text_field :bean_shipment_weight_used_kg %> </td>
          <%= bwb.hidden_field :bean_shipment_id, value: bwb.bean_shipment.id %>
        </tr>
      </table>
  <% end %>

winnow_batches_controller.rb

def new
    @winnow_batch = WinnowBatch.new
    @shipment_options = BeanShipment.where("weight_remaining_kg > ?", 0)
    
    @shipment_options.each do |ship|
        @winnow_batch.bean_winnow_batches.build(bean_shipment_id: ship.id)
    end
end

我在加载视图时收到的错误消息winnow_batch/new“#<ActionView::Helpers::FormBuilder:...的未定义方法'bean_shipment'

如何通过嵌套形式的关联访问 has_many 中的数据,以及如何构建正确数量的嵌套对象并填充条件数据(权重 < 0)?

编辑:我遍历查询结果集以使用正确的数据构建正确数量的对象。但是我怎样才能在视图中显示关联的数据bean_shipment呢?

标签: ruby-on-rails

解决方案


要解决您对错误的问题:
“#<ActionView::Helpers::FormBuilder:...的未定义方法'bean_shipment'

出现此问题是因为您在表单构建器上调用 bean_shipment 方法。

 <%= form.fields_for :bean_winnow_batches do |bwb| %>

|bwb| 指的是表单生成器。
要访问对象(beanwindowbatch),请在表单构建器上调用 .object。

 <%= form.fields_for :bean_winnow_batches do |bwb_form| %>
...
  <tr>
    <td><%= bwb_form.object.bean_shipment.lotcode %></td>
  </tr>
...
 <% end %> 

推荐阅读