Nicolás Aguirre
Nicolás Aguirre

Reputation: 63

belongs_to relation not firing after_update when nullify

In the project i'm working on i have 2 models, user.rb and job.rb.

The user model is related to job, a user can have many job requests and a user can be hired in many jobs but only one user per job can be hired.

User.rb:

  has_many :job, dependent: :nullify, :foreign_key => "hired_contractor_id"

Job.rb:

  belongs_to :hired_contractor, class_name: "User", optional: true

Expected behaviour: When a user is deleted (which that user is hired in a job) i want to change the job status.

For that i'm trying with after_update or after_save but none is fired by a nullify effect on a belongs_to relation.

What am i mising?

Upvotes: 1

Views: 175

Answers (1)

Nicolás Aguirre
Nicolás Aguirre

Reputation: 63

I ended up removing the dependent: :nullify because i found that it doesn't trigger any parent callback.

If you try to update every job in a before_destroy (user.rb) you will not find any job because the relation is gone.

My solution was to remove dependent: :nullify so i still have the job relations to find them in a before_destroy on user.rb and update every job :status and :hired_contractor_id columns manally.

Not the best solution but one that works finally.

Upvotes: 2

Related Questions