Is this the correct way to use way :dependent => :destroy in my RoR app?
This is how my RoR app is setup
note.rb
belongs_to :use开发者_如何学Gor
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.
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
精彩评论