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.
on 2008-12-17 15:15
on 2008-12-17 15:27
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
on 2008-12-17 15:42
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
on 2008-12-17 16:32
Thanks a lot guys!