refactored favorites

This commit is contained in:
r888888888
2013-04-18 20:19:11 -07:00
parent 9372219434
commit 00034f1a17
6 changed files with 38 additions and 20 deletions

View File

@@ -6,4 +6,26 @@ class Favorite < ActiveRecord::Base
def self.destroy_all(hash)
connection.execute("delete from favorites_#{hash[:user_id] % 100} where user_id = #{hash[:user_id]} and post_id = #{hash[:post_id]}")
end
def self.add(post, user)
return if Favorite.for_user(user.id).exists?(:user_id => user.id, :post_id => post.id)
Favorite.create(:user_id => user.id, :post_id => post.id)
Post.update_all("fav_count = fav_count + 1", "id = #{post.id}")
Post.update_all("score = score + 1", "id = #{post.id}") if user.is_privileged?
post.append_user_to_fav_string(user.id)
user.add_favorite!(post)
user.increment!(:favorite_count)
post.add_favorite!(user)
end
def self.remove(post, user)
return unless Favorite.for_user(user.id).exists?(:user_id => user.id, :post_id => post.id)
Favorite.destroy_all(:user_id => user.id, :post_id => post.id)
Post.update_all("fav_count = fav_count - 1", "id = #{post.id}")
Post.update_all("score = score - 1", "id = #{post.id}") if user.is_privileged?
post.delete_user_from_fav_string(user.id)
user.remove_favorite!(post)
user.decrement!(:favorite_count)
post.remove_favorite!(user)
end
end

View File

@@ -525,11 +525,7 @@ class Post < ActiveRecord::Base
end
def add_favorite!(user)
return if favorited_by?(user.id)
append_user_to_fav_string(user.id)
Post.connection.execute_sql("update posts set fav_count = fav_count + 1 where id = #{id}")
Post.connection.execute_sql("update posts set score = score + 1 where id = #{id}") if CurrentUser.is_privileged?
user.add_favorite!(self)
Favorite.add(self, user)
end
def delete_user_from_fav_string(user_id)
@@ -537,11 +533,7 @@ class Post < ActiveRecord::Base
end
def remove_favorite!(user)
return unless favorited_by?(user.id)
Post.connection.execute_sql("update posts set fav_count = fav_count - 1 where id = #{id}")
Post.connection.execute_sql("update posts set score = score - 1 where id = #{id}") if CurrentUser.is_privileged?
delete_user_from_fav_string(user.id)
user.remove_favorite!(self)
Favorite.remove(self, user)
end
def favorited_user_ids

View File

@@ -204,17 +204,11 @@ class User < ActiveRecord::Base
end
def add_favorite!(post)
return if Favorite.for_user(id).exists?(:user_id => id, :post_id => post.id)
Favorite.create(:user_id => id, :post_id => post.id)
increment!(:favorite_count)
post.add_favorite!(self)
Favorite.add(post, self)
end
def remove_favorite!(post)
return unless Favorite.for_user(id).exists?(:user_id => id, :post_id => post.id)
Favorite.destroy_all(:user_id => id, :post_id => post.id)
decrement!(:favorite_count)
post.remove_favorite!(self)
Favorite.remove(post, self)
end
end