问题
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.
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
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.
Thanks in advance...
VIEW CODE (by request):
(Form Partial for Invoices)
<%= 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 %>
(Form Partial for Line Items)
...
<%= 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();
}
回答1:
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
instead of
attr_accessible :line_items
回答2:
Please list your view code, because your bug may be in how you're calling your nested forms. Here's my primer on nested attributes, if it helps:
http://kconrails.com/2010/10/19/common-addresses-using-polymorphism-and-nested-attributes-in-rails/
Following this guide may take care of your problem.
来源:https://stackoverflow.com/questions/4381897/accepts-nested-attributes-not-saving-any-changes