我正在运行 ActiveRecord 3.2.6。鉴于我有这些模型定义:
class Invoice < ActiveRecord::Base
has_many :items, :autosave => true, :dependent => :delete_all
attr_accessible :recipient_email
# This is just a simple wrapper with allows me to build multiple
# items at once and to specify them as a Hash instead of Item.new.
def items=(ary)
super ary.map{|item| item.is_a?(Hash) ? items.build(item) : item}
end
end
Run Code Online (Sandbox Code Playgroud)
class Item < ActiveRecord::Base
belongs_to :invoice
attr_accessible :amount, :description, :invoice_id, :value
end
Run Code Online (Sandbox Code Playgroud)
我的目标是将发票项目直接保存在模型中。当发票是新创建的时,这可以正常工作。一通电话Invoice#save!即可保存所有内容。
> i = Invoice.new(:recipient_email => "foobar@example.org")
> i.items …Run Code Online (Sandbox Code Playgroud)