Reputation:
I have some rails Model Parent
that has_many Child
, and I have this after_create
callback in Parent class
has_many :children
after_create :add_children
def add_children
self.childlren = fetch_some_children
end
However, this doesn't do anything and the children fetched from fetch_some_children
didn't update their foreign keys. Now if I changed the callback to be before_create
instead of after_create
, then it works and children foreign keys are updated, so why does this happen?
Edit: I had some other complex piece of code that resulted in this problem, so it's now fixed.
Upvotes: 0
Views: 45
Reputation: 6100
def add_children
self.childlren = fetch_some_children
self.save # to persist the data
end
When you use before_create
it sets children
and it gets saved, after_create
as it said it is already created, you have to persist your data
Upvotes: 2