2010-12-07 39 views
0

也许我失去了一些明显的(希望),但我遇到了一个奇怪的问题,以嵌套的形式保存记录。这是一个非常基本的设置,其中一个小的复杂因素是我的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(); 
} 
+0

请出示您的视图代码。你使用`fields_for`吗? – nathanvda 2010-12-07 22:08:41

+0

哇,我一直无法发现您发布的代码有任何问题。我倾向于认为这是一个对象问题,与控制器或视图层无关。我现在没有时间深入研究这个问题,希望别人可以跳进来。您是否尝试在控制台中设置属性?如果失败了,你有一个模型问题。如果成功,则问题出现在控制器/视图中。祝你好运,我会稍后再回来查看。 – 2010-12-07 22:23:57

+0

@Jaime:控制台表现超级怪异。我可以创建发票并为新的'line_item'或几个设置属性。当我实际保存时,验证通过,但没有创建line_items(所以我留下了一个空的发票,并没有通知任何错误)。我不能在我的观点中操纵或摧毁任何东西。我要疯了... – Nuby 2010-12-07 22:29:15

回答

3

这里可能的罪魁祸首是attr_accessible。当您使用accepts_nested_attributes_for时,关联的属性名称为association_attributes。所以,你要

attr_accessible :line_items_attributes 

,而不是

attr_accessible :line_items