I have a simple set up of User
and UserProfile
model with User has_one :user_profile
and UserProfile belongs_to :user
.
But I am unable to wrap my head around how Rails defines execution order of after_create
callback and accepts_nested_attributes_for
defined in my model. Lets consider these two cases.
Case 1:
class User < ActiveRecord::Base
has_one :user_profile
accepts_nested_attributes_for :user_profile
after_create :test_test
end
Now, if I create a user(with user_profile_attributes hash too) via the console, the after_create
callback is triggered after the user and its user profile is created.
Case 2:
If the after_create
is placed at the top,
class User < ActiveRecord::Base
after_create :test_test
has_one :user_profile
accepts_nested_attributes_for :user_profile
end
the callback is triggered after a user has been created but before creating a user profile.
Is this the way it is expected to function. What does Rails do internally here? Is the execution sequence simply determined by the order of the code?
Where do I start to dig deeper into or debug this ?
inverse_of
might be useful to solve dependencies and saving problems on create or on save. e.g.has_one :user_profile, inverse_of: :user
– Bendicta