ruby-on-rails - 如何创建和提交一个嵌套表单,其中的值通过关联从 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
呢?
解决方案
要解决您对错误的问题:
“#<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 %>
推荐阅读
- ldap - 使用 OpenLDAP 设置 LDAP 授权
- python - 我应该怎么做才能在 Heroku 上使用 python-magic?
- linux-kernel - 进程控制块的文件格式是什么?
- qt - 如何更改 vlc-qt 媒体显示小部件?
- c# - 如何在 WinForms 中使用 GraphicsPath 填充不同颜色的椭圆?
- google-maps - Googlemaps 中的图像生成器
- jquery - 使用 jquery 从 umbraco 表单中获取变量
- jupyter - 在 Google Colab jupyter notebooks 中为动态生成的文件创建文件下载链接
- angular - 第二次没有在离子中调用函数
- c# - 将 Linq 查询转换为表达式树