# How to build scope for count() & has many polymorphic?

**URL:** <https://www.ruby-forum.com/t/how-to-build-scope-for-count-has-many-polymorphic/172500>\
**Category:** Rails\
**Created:** [July 22, 2009, 2:18pm UTC](https://www.ruby-forum.com/t/how-to-build-scope-for-count-has-many-polymorphic/172500 "2009-07-22T14:18:24Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![yankees26](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/y/eb9ed0/32.png) [@yankees26](https://www.ruby-forum.com/u/yankees26)\
**Post date:** [July 22, 2009, 2:18pm UTC](https://www.ruby-forum.com/t/how-to-build-scope-for-count-has-many-polymorphic/172500/1 "2009-07-22T14:18:24Z")

</div>

Hello, i have the following models in my application:

class Message \< ActiveRecord::Base  
has\_many :comments, :as =\> :commentable, :dependent =\> :destroy,  
:order =\> ‘created\_at ASC’  
end

class Comment \< ActiveRecord::Base  
belongs\_to :commentable, :polymorphic =\> true  
end

I need “commented” named scope, which do the follownig thing:

Message.commented -\> returns all messages where comments is \> 0.

How i can do this?

---

<div class="post-metadata">

**Author:** ![yankees26](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/y/eb9ed0/32.png) [@yankees26](https://www.ruby-forum.com/u/yankees26)\
**Post date:** [July 22, 2009, 4:12pm UTC](https://www.ruby-forum.com/t/how-to-build-scope-for-count-has-many-polymorphic/172500/2 "2009-07-22T16:12:47Z")

</div>

anybody knows?

---

<div class="post-metadata">

**Author:** ![yankees26](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/y/eb9ed0/32.png) [@yankees26](https://www.ruby-forum.com/u/yankees26)\
**Post date:** [July 23, 2009, 12:22pm UTC](https://www.ruby-forum.com/t/how-to-build-scope-for-count-has-many-polymorphic/172500/3 "2009-07-23T12:22:09Z")

</div>

The typical way around this is to turn on counter caching  
for :comments, and filter against that.

–Matt J.

On Jul 22, 8:18 am, Joao S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
