Forum: Ruby on Rails Counter to keep track of references?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
comopasta G. (Guest)
on 2008-12-17 16:15

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?

Thorsten M. (Guest)
on 2008-12-17 16:27
(Received via mailing list)
if you have that defined the Rails way with has_many,


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
Ryan B. (Guest)
on 2008-12-17 16:42
(Received via mailing list)
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.
comopasta G. (Guest)
on 2008-12-17 17:32
Thanks a lot guys!
This topic is locked and can not be replied to.