也許我失去了一些明顯的(希望),但我遇到了一個奇怪的問題,以嵌套的形式保存記錄。這是一個非常基本的設置,其中一個小的複雜因素是我的LineItem模型是雙字關係(:line_items)。但是,我遵循Rails指南,似乎工作正常。accep_nested_attributes不保存任何更改
我的燈具創建了line_items和發票之間的適當關係,並且所有內容都在我的視圖中正確顯示,但我無法正確保存任何line_item記錄(在我的Rails控制檯或我的視圖中)。
class Invoice < ActiveRecord::Base
attr_accessible :line_items #and the rest of my relevant attributes
has_many :line_items, :dependent => :destroy
accepts_nested_attributes_for :line_items, :allow_destroy => true
# Rest of my model code
end
class LineItem < ActiveRecord::Base
attr_accessible :invoice_id #and the rest of my relevant attributes
belongs_to :invoice
end
的line_items_attributes=
方法存在我的發票,但它不保存新發票的任何line_items。更刺激的是,我可以編輯現有的line_items或在事實之後分配它們,但不是一舉成名(嵌套屬性的全部點)?我的意見甚至無法通過發票表單編輯現有的line_items。有任何想法嗎?很高興發佈更多的代碼,但沒有爲了簡潔起見。
在此先感謝...
視圖代碼(按要求):
(表格部分發票)
<%= form_for(@invoice) do |f| %>
<% @invoice.line_items.build unless @invoice.line_items.any? %>
...
<% f.fields_for :line_items do |builder| %>
<%= render 'line_item_fields', :f => builder %>
<% end %>
(表格部分爲行項目)
...
<%= f.collection_select :sku_id, @skus, :id, :name, :prompt => true %>
<%= f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)") %>
(javascript)
function remove_fields(link) {
$(link).previous("input[type=hidden]").value = "1";
$(link).up(".fields").hide();
}
請出示您的視圖代碼。你使用`fields_for`嗎? – nathanvda 2010-12-07 22:08:41
哇,我一直無法發現您發佈的代碼有任何問題。我傾向於認爲這是一個對象問題,與控制器或視圖層無關。我現在沒有時間深入研究這個問題,希望別人可以跳進來。您是否嘗試在控制檯中設置屬性?如果失敗了,你有一個模型問題。如果成功,則問題出現在控制器/視圖中。祝你好運,我會稍後再回來查看。 – 2010-12-07 22:23:57
@Jaime:控制檯表現超級怪異。我可以創建發票併爲新的'line_item'或幾個設置屬性。當我實際保存時,驗證通過,但沒有創建line_items(所以我留下了一個空的發票,並沒有通知任何錯誤)。我不能在我的觀點中操縱或摧毀任何東西。我要瘋了... – Nuby 2010-12-07 22:29:15