accepts_nested_attributes不保存任何更改 [英] accepts_nested_attributes not saving any changes
问题描述
也许我(希望)缺少一些明显的东西,但是我遇到了一个奇怪的问题,即以嵌套形式保存记录.这是一个非常基本的设置,但有一个小的复杂之处,就是我的LineItem模型是两个单词的关系(:line_items).但是,我已经遵循了Rails的指导方针,并且似乎工作正常.
Maybe I'm missing something obvious (hopefully), but I'm encountering a weird problem saving records in a nested form. It's a pretty basic setup, with a minor complication in that my LineItem model is a two-word relationship (:line_items). However, I've followed Rails guidelines and it seems to be working OK.
我的装置在line_items和发票之间建立了正确的关系,并且一切都在我的视图中正确显示,但是我无法获得任何line_item记录来正确保存(在我的Rails控制台或我的视图中).
My fixtures are creating the proper relationships between line_items and invoices, and everything is showing up properly in my views, but I can't get any line_item records to save correctly (in my Rails console or my views).
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或在事实之后分配它们,但不能一fell而就(嵌套属性的整个要点?).我的视图甚至无法通过发票表单编辑现有的line_items.有任何想法吗?很高兴发布更多代码,但是为了简洁起见.
The line_items_attributes=
method exists for my Invoices, but it doesn't save any line_items for new invoices. More irritating, I can edit existing line_items or assign them after the fact, but not in one fell swoop (the whole point of nested attributes?). My views can't even edit existing line_items through the invoice form. Any ideas? Happy to post more code, but didn't for sake of brevity.
预先感谢...
查看代码(应要求):
(发票的部分表格)
<%= 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)
(javascript)
function remove_fields(link) {
$(link).previous("input[type=hidden]").value = "1";
$(link).up(".fields").hide();
}
推荐答案
可能的罪魁祸首是attr_accessible.当您使用accepts_nested_attributes_for时,关联的属性名称为association_attributes.所以你想要
The likely culprit here is attr_accessible. When you use accepts_nested_attributes_for, the name of the attribute for an association is association_attributes. So you want
attr_accessible :line_items_attributes
代替
attr_accessible :line_items
这篇关于accepts_nested_attributes不保存任何更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!