Loading... Cancel

on your active record model define has_many with dependent models. R

October 27th, 2007

i was refactoring our Item model, where we have 3 has_many with 3 mapping models.
as we are not using InnoDB based foreign key constraint, we were searching some sort of reliable solution,
which will take pressure in application layer instead of leaving it to the database.

so later we introduced “:dependent” with has_may relation. here is our top of Item model.
has_many :category_mappings, :dependent => :destroy
has_many :categories, :through => :category_mappings

has_many :property_values, :dependent => :destroy
has_many :properties, :through => :property_value

has_many :item_location_mappings, :dependent => :destroy
has_many :locations, :through => :item_location_mappings

our “dependent” flagship is destroying all related items in the item destroy process which has introduced
our flexibility and reduced a lot of code to manage such stuff in a DRY(ied) manner.

so the following unit test worked fine for us.

rails_dependent_unit_test.gif

some bad side,
dependent delete each and every item one by one, which is big issue when you have a big chunk of dependent data.
but that is not suppose to be common in every context. we have no problem with this issue.

best of luck!

“work for fun”