Closed patmbolger closed 6 years ago
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many
The has_many
's defined destroy method will only destroy
the join records, when used along with the :through
option, not the owned
objects themselves.
If the owned objects must be destroyed, could something like this be valid?
For associations with :through and :dependent :destroy
e.g.
In models/agency_people.rb
before_destroy :dependent_destroy_through
has_many :job_seekers, through: :agency_relations, dependent: :destroy
private
def dependent_destroy_through
self.job_seekers.map(&:destroy)
end
Then integration tests such as
agency_person.destroy
expect(JobSeeker.all).not_to include(job_seeker)
will pass. Both the join records and owned objects will be destroyed
Yes, your code would work if we wanted to destroy any associated job seekers when an agency person is destroyed. However, we do not want to do that. The standard logic of just destroying the record(s) from the join table is what we want here.
Ok, that makes sense. Thanks for the clear up
Add rspec integration tests for all such associations that lack them. (that is, add tests that destroy primary object and confirm that the secondary object is managed as intended by the association statement.
That is, the secondary object is destroyed if the association specifies
destroy
, or primary ID's are nullified if the association specifiesnullify
, etc.