Victor
Victor

Reputation: 13378

Reuse same object in other methods within same model

Using Rails 3.2. I have the following code:

# photo.rb
class Photo < ActiveRecord::Base
  before_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. I don't want it to keep finding the current user every time a record is created/photos_count updated, etc.
  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 and photos_controller.rb because I am following this example: http://www.tkalin.com/blog_posts/multiple-file-upload-with-rails-3-2-paperclip-html5-and-no-javascript

Thanks.

Upvotes: 1

Views: 471

Answers (1)

Tom Harrison
Tom Harrison

Reputation: 14018

Use this

def current_user
  @current_user ||= UserSession.find.user
end

This will cache the value in the instance variable @current_user unless it's nil (first time in the request), in which case it will set it.

Upvotes: 3

Related Questions