title: Scope: Sort by difference between two dates
body: <p>I would like to create a scope which sort data from the closest date to the farthest. </p>
  
  <p>For example I have 3 values:</p>
  
  <pre><code>&lt;Value id: 1, date: '2012-12-20'&gt;
  &lt;Value id: 2, date: '2012-12-28'&gt;
  &lt;Value id: 3, date: '2012-12-31'&gt;
  </code></pre>
  
  <p>Then I would like to sort the date closest to a given date: <code>2012-12-29</code>.<br>
  I should have as result this order: <code>2, 3, 1</code>.<br>
  If I choose <code>2012-12-30</code> the result must be: <code>3, 2, 1</code>.</p>
  
  <p>I tried something like this:</p>
  
  <pre><code>scope :order_by_closest_date, lambda{|time| 
    select("*, (date - DATE('#{time}')) AS time").order("time ASC")
  }
  </code></pre>
  
  <p>But it doesn't work.<br>
  For information: Rails 3.2.9 Ruby 1.9.3 Postgresql 9.1.4.<br>
  Any ideas?</p>