Counter to keep track of references?

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.

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

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

Thanks a lot guys!