views:

29

answers:

1

This is how my RoR app is setup

note.rb

belongs_to :user 
has_many :note_categories
has_many :categories, :through => :note_categories

category.rb

has_many :note_categories
has_many :notes, :through => :note_categories

I want to make it so that when a user deletes a note, the corresponding entry in the note_categories table is deleted as well. Do I use :dependent => :destroy to do that?

Also, if I wanted to make it so that if a user deletes a note, and that means that there are no more notes with the category it had, the category itself was deleted, how would I do that? Thanks for reading.

+2  A: 

I want to make it so that when a user deletes a note, the corresponding entry in the note_categories table is deleted as well. Do I use :dependent => :destroy to do that?

Yes, that's correct.

Also, if I wanted to make it so that if a user deletes a note, and that means that there are no more notes with the category it had, the category itself was deleted, how would I do that?

You use an after_destroy callback.

class Note < ActiveRecord::Base
  belongs_to :user 
  has_many :note_categories, :dependent => :destroy
  has_many :categories, :through => :note_categories      
end 

class Category < ActiveRecord::Base
  has_many :note_categories, :dependent => :destroy
  has_many :notes, :through => :note_categories
end

class NoteCategory < ActiveRecord::Base
  belongs_to :note
  belongs_to :category
  after_destroy { category.destroy  if category.notes.empty? }
end
Marcos Toledo