开发者

Copying Object Attributes with Ruby On Rails 3

I'm copying a object attributes from a Model to another model like this;

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

With this copy, its just copies model attributes only, (Estimate copies as new Invoice) but Estimate model and Invoice model has HABTM relation with "Item" model.

How to create new @invoice object with Estimate and it's Item's together? Confused...

Update:

  • Estimate : has_and_belongs_to_many :items (estimates_items table) accepts_n开发者_Go百科ested_attributes_for :items
  • Invoice : has_and_belongs_to_many :items (invoices_items table) accepts_nested_attributes_for :items
  • Item : belongs_to :estimate belongs_to :invoice

Thanks.


I'm a little confused as to what exactly you're meaning here. Are you wanting to both copy the attrs and create a record in the join table to associate the two at the same time? If so this should do the trick I think (untested)...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜