Skip to content

Commit

Permalink
cleanup favorite references on item deletion
Browse files Browse the repository at this point in the history
  • Loading branch information
blahed committed Nov 15, 2012
1 parent 0beaceb commit 9096a7d
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 10 deletions.
12 changes: 11 additions & 1 deletion app/models/base_item.rb
Expand Up @@ -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
Expand All @@ -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
2 changes: 1 addition & 1 deletion app/models/user.rb
Expand Up @@ -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
Expand Down
9 changes: 1 addition & 8 deletions 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
12 changes: 12 additions & 0 deletions test/models/user_test.rb
Expand Up @@ -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.