Rails:深度复制具有多态子项的记录

时间:2014-10-09 20:49:41

标签: activerecord ruby-on-rails-4

所以我正在寻找和现有的DB记录并复制它。当我做一个简单的.dup时,没有多态资产被重复。

class Contact < ActiveRecord::Base
  belongs_to :user
  has_one :profile, as: :profileable, dependent: :destroy
  has_one :address,   through: :profile
  has_many :phones,   through: :profile
  has_many :photos,   through: :profile
  has_many :emails,   through: :profile
  has_many :socials,  through: :profile
  has_many :websites, through: :profile
end

class Profile < ActiveRecord::Base
  belongs_to :profileable, polymorphic: true
  has_many :addresses, as: :addressable, dependent: :destroy
  has_many :phones, as: :phoneable, dependent: :destroy
  has_many :photos, as: :photable, dependent: :destroy
  has_many :emails, as: :emailable, dependent: :destroy
  has_many :socials, as: :sociable, dependent: :destroy
  has_many :websites, as: :websiteable, dependent: :destroy
end

例如

Contact.new(user_id: 1, profile: User.second.profiles.first.dup).save

成功将个人资料复制到ID为1的用户的新联系人中。但在此示例中,地址,电话,照片,电子邮件,社交和网站信息不会复制。如何复制每个受抚养子女“如果”存在?

1 个答案:

答案 0 :(得分:0)

因为我没有得到答复;我通过一个小元编程编写了自己的代码:

def new_contact_from_existing_profile(user_id, profile_id)
  params = {}
  %w^Address Phone Photo Email Social Website^.each do |poly_child|
    prefix = eval(poly_child).reflect_on_all_associations(:belongs_to).first.name.to_s
    the_type = prefix + "_type"
    the_id = prefix + "_id"
    eval(poly_child).where(the_type.to_sym => "Profile").where(the_id.to_sym => profile_id).each.with_index do |x,i|
      if  params[ eval(poly_child).table_name + "_attributes" ].nil?
        params[ eval(poly_child).table_name + "_attributes" ] = {}
      end
      params[ eval(poly_child).table_name + "_attributes" ][i.to_s] = x.dup.attributes
    end
  end
  Contact.new(
    user_id: user_id,
    profile: Profile.new(
      Profile.find(profile_id).dup.attributes.update params
    )
  ).save
end

对于任何想要深度复制的人,我已经写了一个宝石来为你处理这个问题PolyBelongsTo