如何创建和提交一个嵌套表单,其中的值通过关联从has_many填充



我想创建一个具有许多bean_shipmentsbean_winnow_batcheswinnow_batch

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_batchnew视图中,我想显示所有具有bean_shipment.weight_remaining_kg < 0bean_shipments

用户应该能够通过输入所使用的权重将多个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

我在加载CCD_ 9视图时得到的错误消息";#<的未定义方法"bean_shipment";ActionView::Helpers::FormBuilder:…(

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

编辑:我遍历了一个查询结果集,以使用正确的数据构建正确数量的对象。但是,我如何在视图上显示bean_shipment中的相关数据?

要解决您对错误的问题:
"#<的未定义方法"bean_shipment";ActionView::Helpers::FormBuilder:…(

出现此问题是因为您正在表单生成器上调用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 %> 

最新更新