# Counter to keep track of references?

**URL:** <https://www.ruby-forum.com/t/counter-to-keep-track-of-references/155849>\
**Category:** Rails\
**Created:** [December 17, 2008, 3:15pm UTC](https://www.ruby-forum.com/t/counter-to-keep-track-of-references/155849 "2008-12-17T15:15:28Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![comopasta](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/59ef9b/32.png) [@comopasta](https://www.ruby-forum.com/u/comopasta)\
**Post date:** [December 17, 2008, 3:15pm UTC](https://www.ruby-forum.com/t/counter-to-keep-track-of-references/155849/1 "2008-12-17T15:15:28Z")

</div>

Hi,

I’d like to ask something. I have messages and I have countries. I do  
searches of messages by country. So a country has\_many messages and  
message belongs\_to country.

I have defined a country\_id on the messages country.

Is there a quick way to find how many messages belong to a country  
without going through the messages find? I thought of adding a counter  
to the country table and increase/decrease when a message for that  
country is handled. Is this the right approach?

Thanks.

---

<div class="post-metadata">

**Author:** ![comopasta](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/59ef9b/32.png) [@comopasta](https://www.ruby-forum.com/u/comopasta)\
**Post date:** [December 17, 2008, 3:27pm UTC](https://www.ruby-forum.com/t/counter-to-keep-track-of-references/155849/2 "2008-12-17T15:27:20Z")

</div>

if you have that defined the Rails way with has\_many,  
then:

@country.messages.size

would give you that number.

You can enhance speed for that, by using

has\_many :messages, :counter\_cache =\> true

in countries model.  
This would require a column messages\_count in countries

---

<div class="post-metadata">

**Author:** ![comopasta](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/59ef9b/32.png) [@comopasta](https://www.ruby-forum.com/u/comopasta)\
**Post date:** [December 17, 2008, 3:42pm UTC](https://www.ruby-forum.com/t/counter-to-keep-track-of-references/155849/3 "2008-12-17T15:42:37Z")

</div>

## Also, @country.messages.count will do an SQL COUNT query and return it. Thorsten’s suggestion is quicker of course since you’re only performing one query.

Ryan B.  
Freelancer

> **[frozenplague.net](http://frozenplague.net)**
>
> This domain may be for sale!

---

<div class="post-metadata">

**Author:** ![comopasta](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/59ef9b/32.png) [@comopasta](https://www.ruby-forum.com/u/comopasta)\
**Post date:** [December 17, 2008, 4:32pm UTC](https://www.ruby-forum.com/t/counter-to-keep-track-of-references/155849/4 "2008-12-17T16:32:12Z")

</div>

Thanks a lot guys!
