【发布时间】:2012-02-19 14:47:18
【问题描述】:
我的代码:
class ActiveRecord::Base
def clone!(options = {})
defaults = {:except => [:updated_at, :cerated_at, :id], :shallow => []}
options = defaults.merge(options)
skip_attributes = options[:except] or false #attributes not to clone at all
shallow_attributes = options[:shallow] or false # non-recursivly cloned attributes
options[:except] << self.class.to_s.foreign_key # add current class to exceptions to prevent infinite loop
new_model = self.class.new
self.attributes.each_pair do |attribute, value|
skip_attribute = (skip_attributes ? skip_attributes.map{|a| a.to_s}.include?(attribute) : false)
next if skip_attribute
shallow_copy = (shallow_attributes ? shallow_attributes.map{|s| s.to_s}.include?(attribute) : false)
if attribute =~ /_id\z/ and (not shallow_copy)
# assume reference to a different object
model_table_name = attribute.gsub(/_id\z/, "")
model_name = model_table_name.camelize
referenced_object = model_name.constantize.find(value).clone!(options)
puts attribute.inspect
puts referenced_object.inspect
new_model.send("#{attribute}=", referenced_object[:id])
else
new_model.send("#{attribute}=", value)
end
end
new_model.save!
end
end
所以,调用方法的一种方法是:
b = MyObject.find(432).clone!({:shallow => [:account_id, :user_id, :ext_integration_id, :category_id], :except => [:closed_comment_id]})
问题是 MyObject 有许多 OtherObjects,因此 MyObject 本身并不直接引用 OtherObjects,因为 OtherObjects 具有 MyObject 的外键。
如何找出具有这种关系的模型名称?
【问题讨论】:
标签: ruby-on-rails ruby deep-copy