views:

178

answers:

2

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 try to do this:

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

But this is not deleting the records from the DB. Instead I'm having to do this:

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

...which can't be the best way. So what is the best way, please?

Thanks

+2  A: 
model.options.clear

Reference

Garry Shutler
+1  A: 

Garry is right: model.options.clear

But you can go further and associate it with a model callback, if it fits 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 enforce FK relationships from the database adding DB triggers (if your particular db flavour supports them) appropiately.

I hope that maight help you

Fer