我有一個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