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_user
100回検索します。間違いなくパフォーマンスの問題があります。
- レコードが作成されたり、photos_countが更新されたりするたびに、現在のユーザーを検索し続けたくありません。
- リファクタリング後、これは自分のアカウントを使用して写真をアップロードしている他のユーザーにも影響しますか?
注:いくつかの理由で、を使用できません。この例に従っているためです:counter_cache
http ://www.tkalin.com/blog_posts/multiple-file-upload-with-rails-3-2-paperclip-html5-および-no-javascriptphotos_controller.rb
ありがとう。