title: How to select rows with max(:created_at (Rails 3, PostgreSQL)
body: <p>Want to get (this){example ⬇} data from db.</p>
  
  <p>Have data like this : </p>
  
  <pre><code>=&gt; #&lt;Item id: 2330, asin: “7701C6RHIY", domain: "com”, title: “badfsd”, created_at: "2014-04-04 01:42:28"&gt;
  
  (this) =&gt; #&lt;Item id: 2330, asin: “7701C6RHIY", domain: "com”, title: “badfsd”, created_at: "2014-04-04 03:52:28"&gt;
  
  =&gt; #&lt;Item id: 2330, asin: “7701C6RHIY", domain: "com”, title: “badfsd”, created_at: "2014-04-04 03:42:18"&gt;
  
  =&gt; #&lt;Item id: 2330, asin: “7701C6RHIY", domain: "com”, title: “badfsd”, created_at: "2014-04-04 03:42:22”&gt;
  </code></pre>
  
  <p>+</p>
  
  <pre><code>(this) =&gt; #&lt;Item id: 4331, asin: “R901C6RHIY", domain: “ca”, title: “FSDs”, created_at: "2014-07-04 03:42:28"&gt;
  
  =&gt; #&lt;Item id: 4331, asin: “R901C6RHIY", domain: “ca”, title: “FSDs”, created_at: "2014-04-04 03:42:28"&gt;
  
  =&gt; #&lt;Item id: 4331, asin: “R901C6RHIY", domain: “ca”, title: “FSDs”, created_at: "2014-05-04 03:42:28"&gt;
  </code></pre>
  
  <p>+</p>
  
  <pre><code>(this) =&gt; #&lt;Item id: 571, asin: "BSD1C6RHIY", domain: "co.jp", title: "BRIDGサイズ SCN20.A シルバー”, created_at: "2014-04-04 03:42:28"&gt;
  
  =&gt; #&lt;Item id: 570, asin: "BSD1C6RHIY", domain: "co.jp", title: "BRIDGサイズ SCN20.A シルバー”, created_at: "2014-04-02 03:42:28"&gt;
  
  =&gt; #&lt;Item id: 560, asin: "BSD1C6RHIY", domain: "co.jp", title: "BRIDGサイズ SCN20.A シルバー”, created_at: "2014-04-01 03:42:28"&gt;
  </code></pre>
  
  <p>Result something like (this) data with ids => 2330, 4331, 571</p>
  
  <p>+++ UPDATE +++</p>
  
  <p>Right now this is working for me:</p>
  
  <pre><code> @item_registrations = ItemRegistration.find_all_by_user_id(current_user.id)
   @items = []
   @item_registrations.try(:each) do |i|
     @items += Item.where(:asin =&gt; i.asin, :domain =&gt; i.domain, :user_id =&gt; i    .user_id).order('created_at desc').limit(1)
   end
  </code></pre>
  
  <p>But, this stuff is slow, so, maybe, there is some other way.</p>
  
  <p>+++ UPDATE2 +++</p>
  
  <p>I want to do something like this:</p>
  
  <pre><code>@items = Item.where(:user_id =&gt; current_user.id).where(:created_at =&gt; ("SELECT m    ax(created_at) from Items"))
  </code></pre>
  
  <p>getting a msg -> </p>
  
  <pre><code>PG::InvalidDatetimeFormat: ERROR:  invalid input syntax for type timestamp: "SELECT max(created_at) from Items"
  LINE 1: ... "items"."user_id" = 1 AND "items"."created_at" = 'SELECT ma...
                                                               ^
  : SELECT  "items".* FROM "items"  WHERE "items"."user_id" = 1 AND "items"."created_at" = 'SELECT max(created_at) from Items' LIMIT 1
  </code></pre>