title: ActiveRecord - select first record from each group
body: <p>I want most recent message sent by each users. Here is sample data</p>
  
  <p><strong>Table : conversations</strong></p>
  
  <pre><code>sender  receiver message                        date
  ============================================================
      1   2   "hi"                            "2013-03-04 09:55:01.122074"
      2   1   "hello"                         "2013-03-04 09:55:32.903975"
      1   2   "have you done with the taks?"  "2013-03-04 09:57:46.383007"
      2   1   "almost..."                     "2013-03-04 09:58:55.783219"
      2   1   "should be able to finish 2day" "2013-03-04 09:59:28.950705"
      2   3   "shall we start?"               "2013-03-04 10:01:16.842725"
      3   2   "give me a minute"              "2013-03-04 10:01:41.994589"
      3   2   "let us start"                  "2013-03-04 10:02:14.04551"
  </code></pre>
  
  <p>Where for user with id 2, I should be able to get following two record</p>
  
  <pre><code>1   2   "have you done with the taks?"  "2013-03-04 09:57:46.383007"        
  3   2   "let us start"                  "2013-03-04 10:02:14.04551"
  </code></pre>
  
  <p>Here is my solution</p>
  
  <p><strong>Model : User</strong></p>
  
  <pre><code>class User &lt; ActiveRecord::Base
  has_many :chats_received, class_name: 'Conversation', foreign_key: 'receiver_id',order: "created_at DESC"
  end
  </code></pre>
  
  <p><strong>Model : Conversation</strong></p>
  
  <pre><code>class Conversation &lt; ActiveRecord::Base
    attr_accessible :message, :read
  
    belongs_to :sender, class_name: 'User'
    belongs_to :receiver, class_name: 'User'
  
    def most_recent_chat_received_from_connected_users
      connected_users_chats = . . . # Get all conversations which are sent to current user. e.g., user with id 2
      chats_grouped_by_senders = connected_users_chats.group_by { |conversation| conversation.sender_id }
      chats_grouped_by_senders.inject([]){|memo , (sender_id, conversations)| memo &lt;&lt; conversations.first; memo}
    end
  end
  </code></pre>
  
  <p><strong>Get most recent message from connected users:</strong></p>
  
  <pre><code>user = User.find 2
  user.most_recent_chat_received_from_connected_users
  </code></pre>
  
  <p>Though this solution works, it select and create models for each conversion between two user. Also I feel it is not rails way of getting required rows.</p>
  
  <p>I have been using postgresql. I have been getting following error when I try to use group method on the mode.</p>
  
  <pre><code>ActiveRecord::StatementInvalid: PG::Error: ERROR:  column "conversations.id" must appear in the GROUP BY clause or be used in an aggregate function
  </code></pre>
  
  <p>Is there any better way to get the same results?</p>