Let's consider this example.We have two tables events and tags in our database having a many-to-many relationship between them.So We create a third table taggings behaving as a junction table .So taggings table has a many-to-one relationship against each of these tables.Their corresponding models are Event,Tag,Tagging.Here are their .rb files;
class Event < ActiveRecord::Base
has_many :taggings, dependent: :destroy
has_many :tags , through: :taggings
end
class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :event
end
class Tag < ActiveRecord::Base
has_many :taggings, dependent: :destroy
has_many :events, through: :taggings
end
So, here Tagging table has two foreign key columns namely tag_id and event_id that correspond to the primary key of Tags table and Events table respectively.
Now,taking into consideration the Event model class.When we destroy an object of Event model class ,its associated models to be destroyed will be instantiated and their destroy()
method will be invoked.The same equally holds true when Tag model is in consideration.
Thus it ensures normal object destruction lifecycle, including any callbacks. Destroying children and in turn their grandchildren becomes a really swift operation. It is the normal way to destroy objects that ensures against any anomalies.Whenever in doubt always use dependent: :destroy without any hesitation.
0 Comment(s)