diff --git a/app/controllers/snippets_controller.rb b/app/controllers/snippets_controller.rb index 174df4d..2d486d1 100644 --- a/app/controllers/snippets_controller.rb +++ b/app/controllers/snippets_controller.rb @@ -95,11 +95,6 @@ def ajax_destroy note_id = params[:note_id].to_i if params[:note_id] snippet.destroy - if snippet.source_type == 'web' - source_id = snippet.source_id - WebPage.find(source_id).destroy if Snippet.where(source_type: 'web', source_id: source_id).count.zero? - end - if note_id render_snippets note_id else diff --git a/app/models/bookmark.rb b/app/models/bookmark.rb index 05faedc..e1af11c 100644 --- a/app/models/bookmark.rb +++ b/app/models/bookmark.rb @@ -21,7 +21,7 @@ class Bookmark < ApplicationRecord validates_presence_of :target_id validates_inclusion_of :target_type, in: %w[web] validates_uniqueness_of :display_title, scope: [:manager_id] - before_destroy :destroy_target + after_destroy :destroy_target # ==================================================================== # Public Functions @@ -55,7 +55,7 @@ def url def destroy_target case target_type when 'web' - target.destroy if target.bookmarks.size == 1 && target.snippets.size.zero? + target.destroy if target.deletable? end end end diff --git a/app/models/snippet.rb b/app/models/snippet.rb index 8cddf4e..c17737f 100644 --- a/app/models/snippet.rb +++ b/app/models/snippet.rb @@ -25,6 +25,7 @@ class Snippet < ApplicationRecord validates_inclusion_of :category, in: %w[text image pdf scratch ted youtube], if: "source_type == 'web'" validates_inclusion_of :source_type, in: %w[direct upload web] validates_format_of :description, with: /\.(gif|jpe?g|png)/i, message: 'must have an image extension', if: "source_type == 'web' && category == 'image'" + after_destroy :destroy_source # ==================================================================== # Public Functions @@ -105,4 +106,16 @@ def transferable?(user_id, to_note_id = nil) Note.find_by(id: to_note_id).manager_id == user_id end end + + # ==================================================================== + # Private Functions + # ==================================================================== + private + + def destroy_source + case source_type + when 'web' + source.destroy if source.deletable? + end + end end diff --git a/app/models/web_page.rb b/app/models/web_page.rb index 97e7a50..0d20fec 100644 --- a/app/models/web_page.rb +++ b/app/models/web_page.rb @@ -50,4 +50,8 @@ def self.youtube_id(url) Regexp.last_match(5) end end + + def deletable? + (bookmarks.size + snippets.size).zero? + end end