Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Made `first` finder consistent among database engines by adding a

default order clause (fixes #5103)
  • Loading branch information...
commit 07e5301e697d6a02ed3c079aba07c261d53c1846 1 parent 5603050
@mhfs mhfs authored
View
20 activerecord/lib/active_record/relation/finder_methods.rb
@@ -60,6 +60,9 @@ def find_by!(*args)
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 @@ def find_by!(*args)
# 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 @@ def find_first
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
View
6 activerecord/test/cases/finder_test.rb
@@ -163,6 +163,12 @@ def test_first_bang_missing
end
end
+ def test_first_have_primary_key_order_by_default
+ expected = topics(:first)
+ expected.touch # PostgreSQL changes the default order if no order clause is used
+ assert_equal expected, Topic.first
+ end
+
def test_model_class_responds_to_first_bang
assert Topic.first!
Topic.delete_all

2 comments on commit 07e5301

@mtparet

I'm wondering how many rails app has been impacted by the performance problem of using 'order_by' (before replacing .first by .take)

Please sign in to comment.
Something went wrong with that request. Please try again.