Witam, mam komentarze, które mogą dotyczyć artykułów i newsów (polimorf). Chciałem zrobić sobie buforowanie liczby komentarzy przy danym newsie by za każdym razem nie było wykonywane COUNT(*).
Do modelu comment dopisałem coś takiego:
belongs_to :content, :polymorphic => true, :counter_cache => true
A w bazie do tabeli news dodałem pole :comments_count, :integer, :default => ‘0’
W widoku przy danym newsie liczbę komentarzy do niego wypisuję w ten sposób:
<%= post.comments.count %>
Niestety nie działa to jak powinno: (zrzut z mongrela)
[quote]SQL (165.0ms) SELECT count() AS count_all FROM comments
WHERE (comments
.content_id = 2425 AND comments
.content_type = ‘Post’)
SQL (24.3ms) SELECT count() AS count_all FROM comments
WHERE (comments
.content_id = 2424 AND comments
.content_type = ‘Post’)
SQL (23.9ms) SELECT count() AS count_all FROM comments
WHERE (comments
.content_id = 2423 AND comments
.content_type = ‘Post’)
SQL (23.6ms) SELECT count() AS count_all FROM comments
WHERE (comments
.content_id = 2422 AND comments
.content_type = ‘Post’)
SQL (23.3ms) SELECT count() AS count_all FROM comments
WHERE (comments
.content_id = 2421 AND comments
.content_type = ‘Post’)
SQL (23.5ms) SELECT count() AS count_all FROM comments
WHERE (comments
.content_id = 2420 AND comments
.content_type = ‘Post’)
SQL (23.7ms) SELECT count() AS count_all FROM comments
WHERE (comments
.content_id = 2419 AND comments
.content_type = ‘Post’)
SQL (20.7ms) SELECT count() AS count_all FROM comments
WHERE (comments
.content_id = 2418 AND comments
.content_type = ‘Post’)[/quote]