Using Rails 3.2. I have the following code:
# photo.rb
class Photo < ActiveRecord::Base
after_create :associate_current_user
after_save :increase_user_photos_count
after_destroy :decrease_user_photos_count
private
def associate_current_user
current_user = UserSession.find.user
self.user_id = current_user.id
end
def increase_user_photos_count
current_user = UserSession.find.user
User.increment_counter(:photos_count, current_user.id)
end
def decrease_user_photos_count
current_user = UserSession.find.user
User.decrement_counter(:photos_count, current_user.id)
end
end
Before a new record is created, it searches for the current_user
. This is alright if it's just 1 new record at a time. But if there are 100 records to be created, it's gonna search for the same current_user
100 times. There is definitely performance issue.
How should I refactor this so that the app takes the first query result and reuse it for the next 99 times?
After refactoring, does this affect other users who are also uploading their photos using their accounts?
Note: For some reasons, I can't use the counter_cache
.