1

Railsの使用3.2。私は次のコードを持っています:

# 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

新しいレコードが作成される前に、を検索しますcurrent_user。一度に1つの新しいレコードであれば、これで問題ありません。ただし、作成するレコードが100個ある場合は、同じcurrent_user100回検索します。間違いなくパフォーマンスの問題があります。

  1. レコードが作成されたり、photos_countが更新されたりするたびに、現在のユーザーを検索し続けたくありません。
  2. リファクタリング後、これは自分のアカウントを使用して写真をアップロードしている他のユーザーにも影響しますか?

注:いくつかの理由で、を使用できません。この例に従っているためです:counter_cachehttp ://www.tkalin.com/blog_posts/multiple-file-upload-with-rails-3-2-paperclip-html5-および-no-javascriptphotos_controller.rb

ありがとう。

4

1 に答える 1

3

これを使って

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

@current_userこれにより、値がnil(リクエストで初めて)でない限り、インスタンス変数に値がキャッシュされます。nilの場合は、値が設定されます。

于 2012-11-29T15:09:06.623 に答える