在 Ruby on Rails 中复制父记录和关联子记录的最佳方法? [英] Best way to duplicate parent and associated child records in Ruby on Rails?
问题描述
可能的重复:
ActiveRecord:如何克隆嵌套关联?
我有一个带有 invoices
的表格,而它又可以包含许多 items
.
I have a table with invoices
which in turn can have many items
.
现在在我的 invoices
索引视图中,我想在每个 invoice
旁边放置一个链接,上面写着 Duplicate Invoice.
Now in my invoices
index view I would like to place a link next to each invoice
saying Duplicate Invoice.
如果没有子记录,这会很容易:
Without the child records this would be quite easy:
<%= link_to "Duplicate", new_invoice_path(invoice.attributes) %>
但是,如果发票的items
也应该被复制,这怎么办?
But how can this be done if the invoice's items
should be duplicated as well?
作为一个 Rails 新手,我无法理解这个问题.所有这些都可以通过我的控制器中的 new
操作来处理吗?
As a Rails newbie I can't get my head around this. Can all this be handled by the new
action inside my controller?
def new
@invoice = current_user.invoices.build(:project_id => params[:project_id])
@title = "New invoice"
end
或者我是否需要创建另一个名为例如的函数copy
在我的控制器里面?
Or do I need to create another function named e.g. copy
inside my controller?
最佳做法是什么?
感谢您的任何意见...
Thanks for any input...
推荐答案
逻辑应该在模型中
在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
的动作:
Then in the controller, make an action called duplicate
:
def duplicate
new_invoice = @invoice.deep_dup
redirect to new_invoice
end
这篇关于在 Ruby on Rails 中复制父记录和关联子记录的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!