Can't grab foreign key during after_create callback because it doesn't exist yet!

Posted by Randy on Stack Overflow See other posts from Stack Overflow or by Randy
Published on 2010-03-06T00:24:40Z Indexed on 2010/03/12 7:57 UTC
Read the original article Hit count: 152

I have some models all linked together in memory (parent:child:child:child) and saved at the same time by saving the top-most parent. This works fine.

I'd like to tap into the after_create callback of one of the children to populate a changelog table. One of the attributes I need to copy/push into the changelog table is the child's foreign_key to it's direct parent, but it doesn't exist at the time after_create fires!?!

Without the after_create callback, I can look in the log and see that the child is being saved before it's parent (foreign key blank) then the parent is inserted... then the child is updated with the id from the parent. The child's after_create is firing at the right time, but it happens before Rails has had a chance to update the child with the foreign_key.

Is there any way to force Rails to save such a linkage of models in a certain order? ie.parent, then child (parent foreign_key exists), then that child's child (again, foreign_key is accessible) etc. ?? If not, how would I have my routine fire after a record is created AND get the foreign_key?

Seems a callback like this would be helpful: after_create_with_foreign_keys

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about after-create