ActiveRecord: delete related records

Something I'm not getting ...

I have this in my model:

class Model < ActiveRecord::Base has_many :model_options # a link table for many to many has_many :options, :through => :model_options, :dependent => :destroy, :foreign_key => 'model_id' end 

And I'm trying to do this:

 model = Model.find(id) model.options.delete # also tried model.options.delete_all 

But this is not deleting records from the database. Instead, I have to do this:

 model.options.each do |option| option.delete end 

... which may not be the best way.
So what's the best way please?

+6
ruby-on-rails activerecord
source share
3 answers
 model.options.clear 

Link

+10
source share

Harry is right: model.options.clear

But you can go further and associate it with a model callback if it suits your needs

 class Model < ActiveRecord::Base has_many :model_options # a link table for many to many has_many :options, :through => :model_options, :dependent => :destroy, :foreign_key => 'model_id' # Clear options records before destroy before_destroy :clear_options protected def clear_options options.clear end end 

Or you can use this plugin to match FK relationships from a database adding DB triggers (if your particular db flavor supports them) respectively.

I hope magic helps you

+4
source share

In Rails 3, all you have to do is :dependent => :destroy , and ActiveRecord will take care of the rest

+1
source share

All Articles