Yes. On a Rails’ model association you can specify the :dependent option, which can take one of the following three forms:
:destroy/:destroy_allThe associated objects are destroyed alongside this object by calling theirdestroymethod:delete/:delete_allAll associated objects are destroyed immediately without calling their:destroymethod:nullifyAll associated objects’ foreign keys are set toNULLwithout calling theirsavecallbacks
Note that the :dependent option is ignored if you have a :has_many X, :through => Y association set up.
So for your example you might choose to have a post delete all its associated comments when the post itself is deleted, without calling each comment’s destroy method. That would look like this:
class Post < ActiveRecord::Base
validates_presence_of :body, :title
has_many :comments, :dependent => :delete_all
end
Update for Rails 4:
In Rails 4, you should use :destroy instead of :destroy_all.
If you use :destroy_all, you’ll get the exception:
The :dependent option must be one of [:destroy, :delete_all, :nullify,
:restrict_with_error, :restrict_with_exception]