From 07e5301e697d6a02ed3c079aba07c261d53c1846 Mon Sep 17 00:00:00 2001
From: Marcelo Silveira <marcelo@mhfs.com.br>
Date: Thu, 26 Apr 2012 19:27:55 -0300
Subject: Made `first` finder consistent among database engines by adding a
 default order clause (fixes #5103)

---
 .../lib/active_record/relation/finder_methods.rb     | 20 ++++++++++++++++++--
 1 file changed, 18 insertions(+), 2 deletions(-)

(limited to 'activerecord/lib')

diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 1ceb1949a4..9fd8b49ffb 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -60,6 +60,9 @@ module ActiveRecord
       where(*args).first!
     end
 
+    # Find the first record (or first N records if a parameter is supplied).
+    # If no order is defined it will order by primary key.
+    #
     # Examples:
     #
     #   Person.first # returns the first object fetched by SELECT * FROM people
@@ -67,7 +70,15 @@ module ActiveRecord
     #   Person.where(["user_name = :u", { :u => user_name }]).first
     #   Person.order("created_on DESC").offset(5).first
     def first(limit = nil)
-      limit ? limit(limit).to_a : find_first
+      if limit
+        if order_values.empty? && primary_key
+          order("#{quoted_table_name}.#{quoted_primary_key} ASC").limit(limit).to_a
+        else
+          limit(limit).to_a
+        end
+      else
+        find_first
+      end
     end
 
     # Same as +first+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
@@ -319,7 +330,12 @@ module ActiveRecord
       if loaded?
         @records.first
       else
-        @first ||= limit(1).to_a[0]
+        @first ||=
+          if order_values.empty? && primary_key
+            order("#{quoted_table_name}.#{quoted_primary_key} ASC").limit(1).to_a[0]
+          else
+            limit(1).to_a[0]
+          end
       end
     end
 
-- 
cgit v1.2.3