2011-02-16 43 views
4

我将模型中的对象属性复制到另一个模型中;使用Ruby On Rails 3复制对象属性

@estimate = Estimate.find(params[:estimate_id]) 
@invoice = Invoice.create(@estimate.attributes) 

在该副本中,它只是复制模型只属性, (预算份新的发票),但估算模型和发票模型具有“项”模式HABTM关系。

如何用估计和它的项目一起创建新的@invoice对象?困惑......

更新:

  • 估值:has_and_belongs_to_many:项目(estimates_items表) accepts_nested_attributes_for:项目
  • 发票:has_and_belongs_to_many:项目(invoices_items表) accepts_nested_attributes_for:项目
  • 项目:belongs_to:估计 belongs_to:发票

谢谢。

回答

5

我对你在这里的意义有点困惑。你是否想要复制attrs并在连接表中创建一条记录来同时关联这两条记录?如果是的话,这应该做的伎俩,我认为(未经测试)...

@estimate = Estimate.find(params[:estimate_id]) 
@invoice = Invoice.create(@estimate.attributes.merge(:items => @estimate.items)) 
+0

是的。使用Item属性估算复制为发票“克隆”。项目模型是HABTM与估计和发票的关联。测试了这个代码。它返回“未知属性:估计值”。看起来问题来自嵌套attrs – Harry 2011-02-16 16:19:42