2008/04/06 19:37
어떤 모델의 count를 증가시킬 때,
예를 들어 Issue라는 model이 있고, show 요청이 있을 때마다 이 model의 view_count를 증가시키고 싶다면, 다음과 같은 코드를 생각할 수 있다.
- def hit!
- update_attribute(:view_count, view_count+1)
- end
위 코드는 view_count를 증가시키기는 하지만, 일반적인 save의 과정을 따라가기 때문에 updated_at 역시 변경시킨다. 그리고 오래 걸린다.
view_count만 변경하고 싶다면, query를 직접사용하는 것이 한 방법일 수 있다.
그리고 나처럼 sql이 영 부담스럽다면 increment_counter를 이용할 수도 있다.
- class Issue < ActiveRecord::Base
- def hit!
self.class.increment_counter(:view_count, self.id)
end - end
이 글은 스프링노트에서 작성되었습니다.
'Rails' 카테고리의 다른 글
| [Rails] netbeans에서 haml highlighting 지원 (0) | 2008/04/06 |
|---|---|
| [Rails]controller에 파라미터로 들어온 민감한 데이터를 로그에 남기지 않기 (0) | 2008/04/06 |
| [Rails] increment_counter (0) | 2008/04/06 |
| [Rails] RESTful resource (0) | 2008/03/31 |
| [Rails][ActiveSupport] alias_method_chain (0) | 2008/03/21 |
| [Rails] ActiveRecord의 Callback (0) | 2008/03/21 |