[Nitro] og: automatic deletion of records in M:N relations?

Jonathan Buch john at oxyliquit.de
Sun Aug 27 14:01:56 EDT 2006


> a = Item.new
> a.tags << Tag.new
> a.delete(true) # << this makes a cascade while deleting, should also
> remove the relations

on the other hand, while researching the matter, I found out that  
cascading is the default.  And yes, works with relations, not with  
many_to_many though... Only with simple belongs_to...

I have a solution right here, but it ain't exactly nice...

put in place in joins_many.rb, enchant:


     if through = self[:through]
       # A custom class is used for the join. Use the class
       # table and don't create a new table.
       through = Relation.symbol_to_class(through, owner_class) if  
       join_table = self[:join_table] = store.table(through)

       tmp_join_class = through
       # Calculate the name of the join table.
       join_table = self[:join_table] = join_table_info[:table]
       # Create a join table.
       owner_class.ann :self, :join_tables => [] unless  
       owner_class.ann.self.join_tables! << join_table_info

       # handle for ann.descendants to cascade deletes

       tmp_join_class_name =  
       eval("class #{tmp_join_class_name}; OGTABLE = '#{join_table}'; end;")
       tmp_join_class = constant(tmp_join_class_name)

     owner_key = join_table_info[:owner_key]
     target_key = join_table_info[:target_key]

     unless owner_class.ann.self[:descendants]
       owner_class.ann(:self, :descendants => [])
     owner_class.ann.self.descendants! << [tmp_join_class, owner_key]

     owner_class.module_eval %{
       attr_accessor :#{target_plural_name}


Not exacytly nice, but does what you want :)

It will delete the relationship with the Tag, not the Tag itself.


Feel the love

More information about the Nitro-general mailing list