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
.
1 Answer 1
Remove the callback, and call that code at the level where it's used best.
I.e.:
When you create a batch of records:
#find and cache user
user = UserSession.find.user
# create your 100 records however you want... this is a dumb example
100.times { Post.create!(user: user) }
When you're in a controller, you want to do the same thing, except you're just creating one post.
user = UserSession.find.user
Post.create!(user:user, some:other, params:go_here)
Now that I've written it, it appears if you wanted to DRY up this example, you could wrap it in some class like this:
class CreatesPosts
def self.create(num_records = 1, user = UserSession.find.user)
num_records.times { Post.create!(user:user) }
# might need to tweak to vary up the Post attributes
end
end
-
\$\begingroup\$ For some reasons, it doesn't utilize the
photos_controller.rb
at all. I was using this example to upload the photos: tkalin.com/blog_posts/… \$\endgroup\$Victor– Victor2012年11月29日 15:01:01 +00:00Commented Nov 29, 2012 at 15:01