【问题标题】:accepts_nested_attributes not saving any changesAccepts_nested_attributes_for 不保存任何更改
【发布时间】:2010-12-07 21:41:28
【问题描述】:

也许我遗漏了一些明显的东西(希望如此),但我在以嵌套形式保存记录时遇到了一个奇怪的问题。这是一个非常基本的设置,有一点复杂,因为我的 LineItem 模型是两个字的关系 (:line_items)。但是,我遵循了 Rails 指南,而且它似乎工作正常。

我的设备正在 line_items 和 invoices 之间创建正确的关系,并且所有内容都在我的视图中正确显示,但我无法正确保存任何 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吗?
  • 哇,我无法发现您发布的代码有任何问题。我倾向于认为这是一个对象问题,与控制器或视图层无关。我现在没有时间深入研究这个,希望其他人可以加入。您是否尝试过在控制台中设置属性?如果它失败了,你有一个模型问题。如果成功,则问题出在控制器/视图中。祝你好运,我稍后再回来查看。
  • @Jaime:控制台的行为非常奇怪。我可以为一个或多个新的“line_item”创建发票并设置属性。当我实际保存时,验证通过,但没有创建 line_items(所以我留下了一张空发票,也没有任何错误的通知)。在我看来,我不能操纵或破坏任何东西。我要疯了……

标签: ruby-on-rails ruby-on-rails-3 model nested-attributes


【解决方案1】:

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

attr_accessible :line_items_attributes

而不是

attr_accessible :line_items

【讨论】:

  • 谢谢!这似乎在我的观点中起到了作用。不知道它是否解决了所有问题,但到目前为止工作。我不认为我必须手动将其添加到列表中 - 我认为nested_attributes 会处理它。
【解决方案2】:

请列出您的视图代码,因为您的错误可能在于您调用嵌套表单的方式。如果有帮助,这是我对嵌套属性的入门:

http://kconrails.com/2010/10/19/common-addresses-using-polymorphism-and-nested-attributes-in-rails/

遵循本指南可能会解决您的问题。

【讨论】:

  • 我以前看过您的博客,感谢您的浏览。我会检查你的代码,看看我是否能找出我搞砸的地方......
猜你喜欢
  • 1970-01-01
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-09
  • 2017-10-26
相关资源
最近更新 更多