1
\$\begingroup\$

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.

  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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Nov 29, 2012 at 8:47
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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
answered Nov 29, 2012 at 13:01
\$\endgroup\$
1
  • \$\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\$ Commented Nov 29, 2012 at 15:01

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.