rroblak/seed_dump

Restoring fails for non-continuous Identity column

gowthamgts opened this issue · 1 comments

This works good for table that have no rows deleted in between. However, in a parent-child relationship tables, the foreign key reference is maintained with help of the ID of the parent.

If I delete one row in the parent table and then seed the table again, the children got mapped to different parent due to change in the reference in the parent.

Is there any fix for this, except non-rails solution like mysqldump?

Sample Issue at StackOverflow.

I have this issue too.

I can think of a solution (but don't have the time right now to code up a working solution):

This might not work for appending to a file, but means that you could pull at least one table that you're interested in and ensure that all dependencies would be created and referentially intact.

Interrogate the class for belongs_to associations, then for each record, pull a copy of the associated record, store the attributes in a hash, then prepend the following to the seed output:

association_attributes_hash = model.association.attributes #(simplified for brevity)

association = AssociatedModel.find_or_create_by(association_attributes_hash)

# model.filtered_attributes is all attributes, minus the association_id
MyModel.create! model.filtered_attributes.merge(association_id: association.id)

(This is very rough and off the top of my head, but you get the idea - the key is the find_or_create_by call)

That way, you won't overwrite existing records, and end up with the correct ID in the reference.

Thinking about it - it would need to be a little bit cleverer - whereby the association would have to be processed recursively - ensuring the full dependency tree.

If I discover that I really need this feature, I might have a go at coding it, but I don't need it enough to spare the time right now.

It is a fairly important feature to include though.