1

可能重复:
ActiveRecord:如何克隆嵌套关联?

我有一张桌子,invoices反过来可以有很多items.

现在在我的索引视图中,我想在每个说Duplicate Invoiceinvoices旁边放置一个链接。invoice

如果没有子记录,这将很容易:

<%= link_to "Duplicate", new_invoice_path(invoice.attributes) %>

但是,如果发票items也应该重复,怎么办呢?

作为一个 Rails 新手,我无法理解这一点。这一切都可以通过new我的控制器内部的操作来处理吗?

def new
  @invoice = current_user.invoices.build(:project_id => params[:project_id])
  @title = "New invoice"
end

或者我是否需要copy在我的控制器中创建另一个名为 eg 的函数?

最佳做法是什么?

感谢您的任何输入...

4

2 回答 2

7

逻辑应该在模型中

invoice.rb

def deep_dup
  new_invoice = Invoice.create(self.dup.attributes)
  items.each do |item|
    new_invoice.items.create(item.dup.attributes)
  end
  return new_invoice
end

然后在控制器中,执行一个名为duplicate

def duplicate
  new_invoice = @invoice.deep_dup
  redirect to new_invoice
end
于 2012-11-03T05:07:46.183 回答
0

Maybe something like this in your create action:

def create
  @invoice = Invoice.new(params[:invoice]
   #find duplicate invoice (if exists)
   duplicate_invoice = Invoice.find(params[:duplicate_invoice_id])
   unless duplicate_invoice.nil?
     items = nil
     duplicate_items = duplicate_invoice.items
     duplicate_items.each do |child|
       item = Item.new(child.attributes)
       item.save
       items << item
     end  
   end
   if @invoice.save
     @invoice.items << items #add the duplicate items to the duplicate invoice
     #handle your redirects....
   end
end

Essentially what you can do pass the id of the duplicate invoice to your create action, find the invoice that you intent to duplicate and then process it's children items into an array of duplicate items. The final step is to add those newly duplicated items to your newly duplicated invoice. This is obviously untested and it's going to require a little additional work on your end but I hope you get the gist of the idea. There's probably other ways to accomplish this.

Of course, there are also gems that can do this for you but it's your call.

于 2012-11-02T19:20:03.290 回答