Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


  def associate_current_user
    current_user = UserSession.find.user
    self.user_id =

  def increase_user_photos_count
    current_user = UserSession.find.user

  def decrease_user_photos_count
    current_user = UserSession.find.user

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.

  1. How should I refactor this so that the app takes the first query result and reuse it for the next 99 times?

  2. 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.


share|improve this question

Remove the callback, and call that code at the level where it's used best.


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
share|improve this answer
For some reasons, it doesn't utilize the photos_controller.rb at all. I was using this example to upload the photos:… – Victor Nov 29 '12 at 15:01

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.