[英]ActiveRecord: Can I copy associations?
有沒有辦法將一個模型的關聯復制到另一個模型......
template_model = MyModel.find(id)
new_model = template_model.clone
new_model.children << template_model.children # I want to *copy* children
...這樣我將孩子從模板復制到新模型? (實際上,此代碼將子項從模板移動到新模型)。
我知道我可以手動循環,但是有更簡潔的方法嗎?
謝謝
問題是你正在克隆模板,但沒有克隆它的孩子。 嘗試類似的東西:
template_model = MyModel.find(id)
new_model = template_model.clone
new_model.children << template_model.children.collect { |child| child.clone }
在/ lib下面添加一些。 例如clone_deep.rb。
module CloneDeep
def clone_deep
kopy = clone
self.class.reflect_on_all_associations.each do |association|
next if association.macro == :belongs_to
cloned_object = case association.macro
when :has_many
self.send(association.name).collect { |item| item.clone_deep }
when :has_one
self.send(association.name) && self.send(association.name).clone_deep
else
clone
end
kopy.send("#{association.name}=", cloned_object)
end
return kopy
end
end
在config / initializers /文件夾下創建新的初始化程序。 在這個文件粘貼里面
ActiveRecord::Base.send(:include, CloneDeep)
現在,您可以使用has_one和hos_many關聯來克隆模型。
cloned_person = person.clone_deep
cloned_person.save
#dup
應當被用來代替#clone
,由於屬性不會在后者的情況下,復制。
module Promotion
class Banner
has_many :localizations
has_many :images
def deep_dup!
duplicate = dup
duplicate.save
duplicate.localizations = localizations.collect { |localization| localization.dup }
duplicate.images = images.collect { |image| image.dup }
duplicate
end
end
end
http://api.rubyonrails.org/classes/ActiveRecord/Core.html#method-i-clone http://api.rubyonrails.org/classes/ActiveRecord/Core.html#method-i-dup
嗯,這不是真正的副本。
但你可以做到
new_model.child_ids = template_model.child_ids
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.