Cascading delete in Ruby ActiveRecord?

I followed screencast on rubyonrails.org (creating a blog).

I have the following models:

comment.rb

class Comment < ActiveRecord::Base belongs_to :post validates_presence_of :body # I added this end 

post.rb

 class Post < ActiveRecord::Base validates_presence_of :body, :title has_many :comments end 

Relations between the models work fine, except for one thing - when I delete a post entry, I would expect RoR to delete all related comment entries. I understand that ActiveRecords is database independent, so there is no built-in way to create foreign keys, relationships, ON DELETE, ON UPDATE. So, is there a way to do this (maybe RoR itself could take care of deleting related comments?)?

+41
ruby-on-rails rails-activerecord database-relations
Dec 13 '09 at 15:08
source share
1 answer

Yes. In the Rails model association, you can specify :dependent , which can take one of the following three forms:

  • :destroy/:destroy_all Associated objects are destroyed along with this object by calling their destroy method
  • :delete/:delete_all All related objects are destroyed immediately without calling the :destroy method
  • :nullify foreign keys of all related objects are set to NULL without calling save callbacks

Note that the :dependent parameter :dependent ignored if you have an association :has_many X, :through => Y

So, for your example, you can choose to have the message delete all comments associated with it when the mail itself is deleted, without calling the destroy comment method. It will 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 will get an exception:

Parameter: dependent must be one of [: destroy ,: delete_all ,: nullify ,: restrict_with_error ,: restrict_with_exception]

+76
Dec 13 '09 at 15:28
source share



All Articles