after_create doesn't have access to associated records created during before_created callback?

Viewed 886

I am running into a weird issue, and reading the callbacks RoR guide didn't provide me an answer.

class User < ActiveRecord::Base
...
has_many :company_users, dependent: :destroy
has_many :companies, through: :company_users
has_many :user_teams, dependent: :destroy
has_many :teams, through: :user_teams

before_create :check_company!
after_create :check_team

def check_company!
  return if self.companies.present?
  domain = self.email_domain
  company = Company.find_using_domain(domain)
  if company.present?
    assign_company(company)
  else
    create_and_assign_company(domain)
  end
end 

def check_team
  self.companies.each do |company|
    #do stuff
  end
end
...
end

The after_create :check_team callback is facing issues because the line

self.companies.each do |company|

Here, self.companies is returning an empty array [] even though the Company and User were created and the User was associated with it. I know I can solve it by making it a before_create callback instead. But I am puzzled!

Why does the after_create callback not have access to self's associations after the commit?

Solution: Please read my comments in the accepted answer to see the cause of the problem and the solution.

1 Answers
Related