在nested_forms中更新

update in nested_forms

本文关键字:更新 forms nested      更新时间:2023-09-26

我使用的是Rails 3.0.3
我有一个模型Bill:

class Bill < ActiveRecord::Base
   has_many :entries    
   accepts_nested_attributes_for :entries
end

在我的账单视图中,我使用嵌套表单在账单中创建新条目,并使用Javascript插入现有条目,此时,没有bill_id:

$("#row" + nested_form_id).append("<input type='hidden' name='bill[entries_attributes][" + nested_form_id + "][id]' id='bill_entries_attributes_" + nested_form_id + "_id' value='" + id +"' >");

当我提交表单时,我得到这个错误:

ActiveRecord::RecordNotFound (Couldn't find Entry with ID=127 for Bill with ID=):
  app/controllers/bills_controller.rb:121:in `new'
  app/controllers/bills_controller.rb:121:in `create'

那么问题是,当我提交

时,rails正在查找bills中的条目

知道我该如何解决这个问题吗?

我不知道如何使用嵌套表单来实现这一点,所以我将已经存在的条目手动设置为账单:

nested_entries = {}      
params[:bill][:entries_attributes] = {}  

params[:entries].each_pair do |key, value|    
   if value[:id].nil?
      params[:bill][:entries_attributes][key] = value 
   else 
     nested_entries[key] = value
   end                             
end           
@bill = Bill.new(params[:bill])  
@bill.save  
bill_id = @bill.id        
nested_entries.each_pair do |key, value|   
   @entry = Entry.find(value[:id])    
   value[:bill_id] = bill_id                            
   @entry.update_attributes(value) 
end