# Counting result "polymorphically"

**URL:** <https://www.ruby-forum.com/t/counting-result-polymorphically/178497>\
**Category:** Rails\
**Created:** [November 5, 2009, 2:37pm UTC](https://www.ruby-forum.com/t/counting-result-polymorphically/178497 "2009-11-05T14:37:59Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Geoffroy\_G](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/f17d59/32.png) [@Geoffroy\_G](https://www.ruby-forum.com/u/Geoffroy_G)\
**Post date:** [November 5, 2009, 2:37pm UTC](https://www.ruby-forum.com/t/counting-result-polymorphically/178497/1 "2009-11-05T14:37:59Z")

</div>

Hello,

I have the following situation in a rails application, where A, B and  
C are models (objects) and are linked in the following way:

A :has\_many B  
A :has\_many C, :as =\> :sumtinable

B :belongs\_to A  
B :has\_many C, :as =\> :sumtinable

C :belongs\_to :sumtinable, :polymorphic =\> true

I want to count all the Cs that belongs to A (directly and through B).  
I came up with a query:  
select count(\*) from C where sumtinable\_type=‘B’ AND sumtinable\_id IN  
(select id from B where A\_id=1) OR sumtinable\_type=‘A’ AND  
sumtinable\_id=1  
The query works and fill my needs but I would like to know if there’s  
a Rails (efficient) way of doing the same thing?  
I would like the database to do the work and avoid iteration in Ruby.

Regards

Geoffroy
