diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 9fd8b49ffb3c10ff389694fb9e7e388efcbc53d7..4a41f1ea8bd43790621ba8da7c05f0547f0c5a61 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -87,6 +87,9 @@ def first! first or raise RecordNotFound end + # Find the last record (or last N records if a parameter is supplied). + # If no order is defined it will order by primary key. + # # Examples: # # Person.last # returns the last object fetched by SELECT * FROM people @@ -94,8 +97,8 @@ def first! # Person.order("created_on DESC").offset(5).last def last(limit = nil) if limit - if order_values.empty? - order("#{primary_key} DESC").limit(limit).reverse + if order_values.empty? && primary_key + order("#{quoted_table_name}.#{quoted_primary_key} DESC").limit(limit).reverse else to_a.last(limit) end