I am trying to perform a query like the following using ActiveRecord and Rails 3:
select count(*), * from messages group by thread_id
I am trying to build the inbox of a simple threaded message system. The point of this query is to collapse all Message object’s to only the most recent one per thread and to also retrieve the size of the thread.
Alternatively, I could just retrieve all the top Messages per thread (simply by removing the count(*)) and then perform the count as a separate query per group of messages, but this seems horribly inefficient.
Does anyone have any ideas? Is there a way to do this in ActiveRecord?
To get rails (3) to generate the query you want, try:
The number of messages in the thread will then be available as the
thread_sizeattribute of the Message records that are returned.Should you find that this query starts to become slow as your database grows larger, you might want to look into Rails’
counter_cachefunctionality (see Section 4.1.2.4 of the ActiveRecord Rails Guide).