Duplicar el registro de ActiveRecord y mantener todas las relaciones

My dilemma is that I need to re-assign all records in a table a new id, for legacy reasons, but this table already has a lot of relationships with different models that depend on it having its old id. I'd like to come up with a good way to re-assign the id's and maintain all relationships, but I've had no luck myself. Any advice is appreciated.

Muchas Gracias

preguntado el 04 de julio de 12 a las 08:07

2 Respuestas

This solution assumes that the foreign key column name is always the same in all tables. It goes through all the tables and changes the old id with the new one.

model_id = "model_id" #foreign key name for that model
old_id = ... #model old id
new_id = ... #model new id

models = ActiveRecord::Base.send(:descendants)
for m in models do
  if m.column_names.include(model_id)
    m.where("#{model_id} = ?", old_id).update_all(model_id => new_id)


También podrías usar reflect_on_all_associations on models, traverse all has_many relationships and change the foreign keys.

Respondido 05 Jul 12, 11:07

It also has some polymorphic relationships, for which additional code would have to be written. I think this will be helpful though. - D-Nice

Yes, you have to be extra careful! I have updated the answer with an alternative method. Please accept the answer if it is. - wawa loo

what about add new field like "extra id" to this table and don't do anything with your old id to keep it stable and use your extra id to do what you want? Sorry I can't think anything better than this solution.

** so you can still use your extra id to link to your old id.

Respondido 04 Jul 12, 09:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.