Rails手动设置视图中的嵌套属性

我很难理解布局视图的方式,以便为嵌套窗体正确嵌套属性。Rails手动设置视图中的嵌套属性

我PARAMS这个样子......

Parameters: {"utf8"=>"✓", 

"authenticity_token"=>"retsty/G2I1FyYybXm9kVaZi+aPjQm4jsmLdLW3wxsc=",

"receipt"=>{"receipt"=>"", "receipt_date(1i)"=>"2014", "receipt_date(2i)"=>"9", "receipt_date(3i)"=>"19",

"po_receipts_attributes"=>[

{"jobquote_order_id"=>{"3"=>"", "5"=>""}, "qty"=>"30"},

{"qty"=>"11"}

]},

"commit"=>"Receive"}

po_receipts_attributes阵列没有正确嵌套的哈希值。

格式:po_receipts_attributes: [{jobquote_order_id: <value>, qty: <value>}, {jobquote_order_id: <value>, qty: <value>}]

据http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html,我的PARAMS应该是这样的......

Parameters: {"utf8"=>"✓", 

"authenticity_token"=>"retsty/G2I1FyYybXm9kVaZi+aPjQm4jsmLdLW3wxsc=",

"receipt"=>{"receipt"=>"", "receipt_date(1i)"=>"2014", "receipt_date(2i)"=>"9", "receipt_date(3i)"=>"19",

"po_receipts_attributes"=>[

{"jobquote_order_id"=>"3", "qty"=>"30"},

{"jobquote_order_id"=>"5", "qty"=>"11"}

]},

"commit"=>"Receive"}

我似乎无法获得的方式嵌套的视图正确属性。我已经尝试了许多不同的语法。

在我看来,我有以下代码...

= hidden_field "receipt[po_receipts_attributes][][jobquote_order_id]", jq_o.id 

= text_field_tag "receipt[po_receipts_attributes][][qty]", ""

HTML输出...

<td> 

<input id="receipt_po_receipts_attributes__jobquote_order_id_3" name="receipt[po_receipts_attributes][][jobquote_order_id][3]" type="hidden" />

<input id="receipt_po_receipts_attributes__qty" name="receipt[po_receipts_attributes][][qty]" type="text" value="" />

</td>

<td>

<input id="receipt_po_receipts_attributes__jobquote_order_id_5" name="receipt[po_receipts_attributes][][jobquote_order_id][5]" type="hidden" />

<input id="receipt_po_receipts_attributes__qty" name="receipt[po_receipts_attributes][][qty]" type="text" value="" />

</td>

什么是处理的最佳方式?

回答:

应该是这样的:

jobquote_orders.each_with_index do |jq_o, i| 

= hidden_field_tag "recepit[po_receipts_attributes][#{i}][jobquote_order_id]", jq_o.id

= text_field_tag "receipt[po_receipts_attributes][#{i}][qty]", ""

这应该产生PARAMS:

"po_receipts_attributes" => { 

"0" => {"jobquote_order_id"=>"3", "qty"=>"30"},

"1" => {"jobquote_order_id"=>"5", "qty"=>"11"}

}

以后可以,(如你在你的问题中指定手动)保存:

params[:receipt][:po_receipts_attributes].values.each do |v| 

pr = PoReceipt.find(v['jobquote_order_id'].to_s)

pr.update_atributes(v.except('id'))

end

回答:

你应该有一个整数内[]喜欢里面:

= hidden_field "recepit[po_receipts_attributes][1][jobquote_order_id]", jq_o.id 

= text_field_tag "receipt[po_receipts_attributes][1][qty]", ""

该整数是什么让属性在一起的时候Rails的解析形式身体进入params哈希表。每组po_receipt_attributes将需要一个不同的ID。如果您生成字段服务器端,您可以使用fields_for,并且ID将自动为您管理。

回答:

尝试使用fields_for作为以下内容:

<%= form_for @receipt do |receipt_form| %> 

<%= receipt_form.fields_for :po_receipts do |po_receipts_fields| %>

<%= po_receipts_fields.hidden_field :jobquote_order_id, jq_o.id %>

<%= po_receipts_fields.text_field :qty %>

<% end %>

<% end %>

以上是 Rails手动设置视图中的嵌套属性 的全部内容, 来源链接: utcz.com/qa/259035.html

回到顶部