Rails accept_nested_attributes无效

时间:2011-03-01 22:20:27

标签: ruby ruby-on-rails-3 activerecord

class Invoice < ActiveRecord::Base
  attr_accessible :line_items_attributes
  accepts_nested_attributes_for :line_items
  has_many :line_items
end

class LineItem < ActiveRecord::Base
  belongs_to :invoice

  def prepopulate_with(l_items)
    unless l_items.empty?
      self.line_items = l_items
    end
  end
end

class InvoiceController < ApplicationController
  def new
    @invoice = Invoice.new
    if params[:line_items]
      line_items = params[:line_items].map{|li| LineItem.find(li)}
      #prepopulate_with just set @invoice.line_items = whatever_array_of_line_items that was passed in
      @invoice.prepopulate_with(line_items)
    end
  end

  def create
    @invoice = Invoice.new(params[:invoice])
    if @invoice.save
      flash[:notice] = "Successfully created invoice."
      redirect_to @invoice
    else
      render :action => 'new'
    end
  end

end

行项目在发票之前创建。所以他们会有自己的ID。我基本上在新动作上使用line_items预加载Invoice.new。包含line_items(带有id)的嵌套发票形式随后会发布到创建操作。

错误:

ActiveRecord::RecordNotFound in InvoicesController#create

Couldn't find LineItem with ID=21 for Invoice with ID=

我已经包含了以下表格的相关部分:

<% f.fields_for :line_items do |li| %>
  <%= li.text_field :description %>
  <%= li.text_field :amount %>
<% end %>

0 个答案:

没有答案