也许我遗漏了一些明显的东西(希望如此),但我在以嵌套形式保存记录时遇到了一个奇怪的问题。这是一个非常基本的设置,有一个小麻烦,因为我的 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();
}