我有一个 has_many :through 表单,我无法获得额外的属性来发布到数据库。我在某处弄脏了参数名称。我可以获取要发布的外键,但我有另一个要在连接表中跟踪的属性。请记住,这是一个 100% 基于 ajax 的表单。这是我所知道的
编辑:在研究了类似的问题后,我知道我应该构建表单属性,但我发现的代码由于某种原因不起作用。这里有一些资源。
http://railsforum.com/viewtopic.php?id=20203
我不明白的是附加 product_ids 是内置在导轨中的。这些价值观发布。为什么很难将 quantity_shipped 属性附加到该数组?
Models and Relationships
Shipment has_many :products :through => :product_shipments
Product has_many :shipments :through => :product_shipments
ProductShipments belongs_to :shipment, belongs_to :product
ProductShipments table
t.integer :shipment_id
t.integer :product_id
t.integer :qty_shipped <-- This is the Problem Child
此部分循环显示来自某个供应商的所有产品几次。它为 product_ids 生成一个数组,为 product_shipments 数量生成另一个数组。
_product_shipments.html.erb。
<div id="product_shipments_container">
<h3>Assign Products to Ship</h3>
<ul class="product_shipments" id="product_shipments">
<% Product.by_client(@client_id).each do |product| %>
<%= content_tag_for :li, product, :value => product.id do %>
<%= hidden_field_tag("shipment[product_ids][]", product.id) %>
<%= product.product_name %><%= text_field_tag("product_shipments[qty_shipped]")%> <--This is where the issue lies
<% end %>
<% end %>
</ul>
</div>
这是提交表单时的相关 POST 数据
"product_ids"=>["1", "3"]}, "product_shipments"=>{"qty_shipped"=>["32", "23"]}
这是发送到数据库的 sql
INSERT INTO `product_shipments` (`product_id`, `qty_shipped`, `shipment_id`)
VALUES (1, NULL, 155)
INSERT INTO `product_shipments` (`product_id`, `qty_shipped`, `shipment_id`)
VALUES (3, NULL, 155)
这是我的控制器中的操作
def create
@shipment = Shipment.new(params[:shipment])
@product_shipments = @shipment.product_shipments.build(params[:product_shipments])
[:qty_shipped]) <- 不正确,但如果@shipment.save respond_with @shipment, :location => shipping_url else flash[:notice]= "Not saved" end end
这是我遇到的最后一个问题。
TypeError (can't convert Symbol into Integer):
app/controllers/shipments_controller.rb:24:in `[]'
app/controllers/shipments_controller.rb:24:in `create'
知道了。使用下面的正确答案进行更改后。我能够将控制器更正为以下内容
@product_shipments = @shipment.product_shipments.build(params[:product_shipments])