title: Sorting array by time attribute in Rails
body: <p>I have an array of appointment objects, and I would like to sort by starts_at attribute.</p>
  
  <p><code>my_array.uniq.sort_by! {|obj| obj.starts_at}</code></p>
  
  <p>However, I got the following error:
  <code>comparison of ActiveSupport::TimeWithZone with nil failed</code></p>
  
  <p>I am sure I don't have any nil value for starts_at. What's the problem here? 
  Also, how can I sort by descending?</p>
  
  <p><strong>Update 1:</strong> I realized that uniq! gives me nil when I call .all method to my Appointment class. Without uniq, it works fine.</p>
  
  <p><code>Appointment.all.uniq!</code></p>
  
  <p><strong>Update 2:</strong> I can't apply minus to obj.starts_at. It gives me error:method - can't be found with UTC time format. Probably b/c time does not allowed to be zero. Any thoughts on overcome this?</p>
  
  <p><strong>Update 3:</strong> <code>my_array.uniq.sort { |x, y| (x.starts_at || nil) &lt;=&gt; (y.starts_at || nil)}</code> works in console, but when I ran my app, it says <code>comparison of Event with Event failed</code></p>
  
  <p><strong>Last update:</strong> The following works:</p>
  
  <p><code>@events.sort_by!{|obj| (obj.starts_at.nil? ? 3.years.ago : obj.starts_at.utc)}</code></p>
  
  <p>I need to convert date format to .utc, and handle missing starts_at (sorry I don't know why I have missing starts_at attribute on an object)</p>