The following block of code is how my model looks.
class MyModel < ActiveRecord::Base
belongs_to :parent_model
after_create :create_model
after_update :update_model
def create_model
# some code goes here
puts "Parent id: " + self.parent_model_id.to_s
# parent_model_id is nil here
end
def update_model
puts "Parent id: " + self.parent_model_id.to_s
# parent_model_id is as it should be
end
end
I want to access the value of its foreign key at the end of after_create
, but it is nil
. It throws an exception even though the other fields are not nil
i.e., the fields of the model itself. However, the foreign key is nil.
If I try to access the foreign key using after_update
, it works.
Why is the foreign key set to null when using the action after_create
in the model?
Rails wraps its changes to a database inside a transaction, and after_create
and after_update
callbacks run inside that transaction. This means that when you call an after_create
method the changes to the database are not implemented, which will result in a null
value for the 'parent_model_id'.
An after_update
callback occurs when a record is created and updated. In that case, the 'parent_model_id' will be always available and an error is not thrown.
You can use another callback named after_commit
. It is called when all changes to a database are completed, and it occurs in both cases; thus, creating a new record and updating an existing one.