aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/relation/finder_methods.rb
diff options
context:
space:
mode:
authorBrian Christian <brchristian@gmail.com>2016-02-10 13:34:35 -0800
committerBrian Christian <brchristian@gmail.com>2016-02-27 11:10:19 -0800
commit048fd13ccdb9a314e54771cb17a0a5d56d0a8d3d (patch)
tree61d1fd611898b4b6cf6ddb34ef54b83abfd50478 /activerecord/lib/active_record/relation/finder_methods.rb
parent3174b5f92a43e4bfdf4f833389b1ac819ac2cdc5 (diff)
downloadrails-048fd13ccdb9a314e54771cb17a0a5d56d0a8d3d.tar.gz
rails-048fd13ccdb9a314e54771cb17a0a5d56d0a8d3d.tar.bz2
rails-048fd13ccdb9a314e54771cb17a0a5d56d0a8d3d.zip
AR #second_to_last tests and finder methods
Diffstat (limited to 'activerecord/lib/active_record/relation/finder_methods.rb')
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb16
1 files changed, 12 insertions, 4 deletions
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 0037398554..245976dc2b 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -255,13 +255,13 @@ module ActiveRecord
# Person.offset(3).third_to_last # returns the third-to-last object from OFFSET 3
# Person.where(["user_name = :u", { u: user_name }]).third_to_last
def third_to_last
- find_nth(-3)
+ find_nth_from_last 3
end
# Same as #third_to_last but raises ActiveRecord::RecordNotFound if no record
# is found.
def third_to_last!
- find_nth!(-3)
+ find_nth_from_last 3 or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]")
end
# Find the second-to-last record.
@@ -271,13 +271,13 @@ module ActiveRecord
# Person.offset(3).second_to_last # returns the second-to-last object from OFFSET 3
# Person.where(["user_name = :u", { u: user_name }]).second_to_last
def second_to_last
- find_nth(-2)
+ find_nth_from_last 2
end
# Same as #second_to_last but raises ActiveRecord::RecordNotFound if no record
# is found.
def second_to_last!
- find_nth!(-2)
+ find_nth_from_last 2 or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]")
end
# Returns true if a record exists in the table that matches the +id+ or
@@ -561,6 +561,14 @@ module ActiveRecord
relation.limit(limit).to_a
end
+ def find_nth_from_last(index)
+ if loaded?
+ @records[-index]
+ else
+ reverse_order.offset(index-1).first
+ end
+ end
+
private
def find_nth_with_limit_and_offset(index, limit, offset:) # :nodoc: