控制器更新方法
class InvoicesController < ApplicationController
def update
@invoice = Invoice.find(params[:id])
respond_to do |format|
if @invoice.update_attributes(params[:invoice])
format.html { redirect_to invoices_path }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @invoice.errors}
end
end
end
end
楷模
发票.rb
class Invoice < ActiveRecord::Base
has_many :invoice_line_items,:dependent => :destroy
accepts_nested_attributes_for :invoice_line_items,:allow_destroy => true
attr_accessible :invoice_dt, :invoice_no,:invoice_line_items_attributes,:amount_due,:tax1,:tax2,:tax3,:tax4,:tax5,:tax1_value,:tax2_value,:tax3_value,:tax4_value,:tax5_value
attr_accessor :amount_due,:tax1,:tax2,:tax3,:tax4,:tax5,:tax1_value,:tax2_value,:tax3_value,:tax4_value,:tax5_value
invoice_line_item.rb
class InvoiceLineItem < ActiveRecord::Base
belongs_to :invoice
attr_accessible :invoice_id, :item_description, :item_no, :quantity, :unit_price,:taxes,:tax1,:tax2,:tax3,:tax4,:tax5
attr_accessor :tax1,:tax2,:tax3,:tax4,:tax5
serialize :taxes, Hash
before_validation :my_taxes
def my_taxes
debugger
self.taxes = {"tax1" => self.tax1,"tax2" => self.tax2,"tax3" => self.tax3,"tax4" => self.tax4,"tax5" => self.tax5}
end
end
当我尝试更新数据时会产生问题。在更新日期,当我用调试器检查它但它没有保存在数据库中时,我得到了所有更新的值。我发现一个原因是“add_taxes”方法在创建中成功调用但在更新操作中没有调用。还要记住我的“taxes”变量是序列化的,我使用了accepted_nested_attributes _for。
谁能帮帮我吗。