2014-10-09 3 views
0

Итак, я ищу, чтобы взять и записать существующую запись и дублировать ее. Когда я делаю простой .dup, ни один из полиморфных активов не дублируется.Rails: Глубокий дубликат записи с полиморфными детьми.

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 

ли успешно скопировать профиль в новый контакт для пользователя с идентификатором 1. Но адрес, телефон, фото, электронная почта, и социального характера на сайте информация не скопируйте в этом примере. Как скопировать каждый зависимый ребенок «если» он существует?

ответ

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

Смежные вопросы