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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
13d7a3ab12ec57e0d372d7115362cb91?d=identicon&s=25 comopasta Gr (comopasta)
on 2008-12-17 15:15
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.
2d8132658d56e51f19ace1c68e48b6aa?d=identicon&s=25 Thorsten Mueller (thorsten)
on 2008-12-17 15:27
(Received via mailing list)
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
9a2a53db8e9b4476038c94a64b32833f?d=identicon&s=25 Ryan Bigg (ryan-bigg)
on 2008-12-17 15: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 Bigg
Freelancer
http://frozenplague.net
13d7a3ab12ec57e0d372d7115362cb91?d=identicon&s=25 comopasta Gr (comopasta)
on 2008-12-17 16:32
Thanks a lot guys!
This topic is locked and can not be replied to.