我有一个has_many:通过表单我无法获得额外的属性发布到数据库。我弄错了某处的参数名称。我可以获得外键发布,但我有另一个属性,我试图追踪连接表中。请记住,这是一个100%基于ajax的表单。这是我所知道的Rails 3.2 has_many通过表单提交
编辑: 经过研究类似的问题,我明白我应该建立表单属性,但我发现的代码由于某种原因不起作用。这里有一些资源。
http://railsforum.com/viewtopic.php?id=20203
Rails 3, nested multi-level forms and has_many through
我不明白的是,安装在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"]}
这是发送到数据库
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)
这里SQL是在我的控制器的动作
def create
@shipment = Shipment.new(params[:shipment])
@product_shipments = @shipment.product_shipments.build(params[:product_shipments])
[:qty_shipped ])< - 不正确的,但是这是我走到这一步,如果 @ shipment.save respond_with @shipment,:位置=> shipments_url 其他 闪光灯[:声明] = “不保存” 结束 结束
这是我遇到的最后一个问题。
TypeError (can't convert Symbol into Integer):
app/controllers/shipments_controller.rb:24:in `[]'
app/controllers/shipments_controller.rb:24:in `create'
GOT IT。使用下面的正确答案进行更改后。我能控制纠正以下
@product_shipments = @shipment.product_shipments.build(params[:product_shipments])
你的意思是写'text_field_tag(“shipment_products [qty_shipped] []”)'? – cdesrosiers
它似乎没有区别。它仍然输入一个空值 – ctilley79
你的模型是否有'has_many:shipment_products'和'accep_nested_attributes_for:shipment_products'?你为什么不用'fields_for'?你知道'simple_form'还是'formtastic'?如果您想要动态添加货件,请查看[cocoon](https://github.com/nathanvda/cocoon)gem。 – nathanvda