Skip to content
Browse files

cleanup favorite references on item deletion

  • Loading branch information...
1 parent 0beaceb commit 9096a7ddf245425f1867efa93e35c00392710109 @blahed committed Nov 14, 2012
Showing with 25 additions and 10 deletions.
  1. +11 −1 app/models/base_item.rb
  2. +1 −1 app/models/user.rb
  3. +1 −8 test/models/favorite_test.rb
  4. +12 −0 test/models/user_test.rb
View
12 app/models/base_item.rb
@@ -10,9 +10,10 @@ class BaseItem
has_and_belongs_to_many :groups, :inverse_of => nil
validates_presence_of :title
-
validate :groups_are_allowed
+ after_destroy :cleanup_references
+
def self.group_ids
all.only(:group_ids).collect{ |ms| ms.group_ids }.flatten.uniq
end
@@ -31,4 +32,13 @@ def groups_are_allowed
errors.add(:base, "The following groups are invalid `#{invalid_groups.join(', ')}'") unless invalid_groups.empty?
end
+
+ def cleanup_references
+ favorites = Favorite.where(:item_type => self.class.name, :item_id => self._id)
+
+ favorites.each do |favorite|
+ user = favorite.user
+ user.favorites.find(favorite._id).destroy
+ end
+ end
end
View
2 app/models/user.rb
@@ -14,7 +14,7 @@ class User
index :username, :unique => true
has_and_belongs_to_many :groups
- has_many :favorites
+ has_many :favorites, :dependent => :destroy
validates_presence_of :username
validates_uniqueness_of :username, :case_sensitive => false
View
9 test/models/favorite_test.rb
@@ -1,11 +1,4 @@
-require "minitest_helper"
+require 'minitest_helper'
describe Favorite do
- before do
- @favorite = Favorite.new
- end
-
- it "must be valid" do
- @favorite.valid?.must_equal true
- end
end
View
12 test/models/user_test.rb
@@ -37,4 +37,16 @@
@user.favorites.size.must_equal 1
end
+ it "removes items from a users favorites after item deletion" do
+ note = FactoryGirl.create(:note)
+
+ @user.favorite!(note)
+ @user.reload
+ @user.favorites.size.must_equal 1
+
+ note.destroy
+ @user.reload
+ @user.favorites.must_be :empty?
+ end
+
end

0 comments on commit 9096a7d

Please sign in to comment.
Something went wrong with that request. Please try again.