diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb index 516a8881aba337297e9f462e2ab634a91ea7a88a..7e15a8e8e5d7a9452d190bee4ab88ecbc3073617 100644 --- a/activerecord/lib/active_record/result.rb +++ b/activerecord/lib/active_record/result.rb @@ -92,18 +92,9 @@ def [](idx) hash_rows[idx] end - # Returns the first record from the rows collection. - # If the rows collection is empty, returns +nil+. - def first - return nil if @rows.empty? - Hash[@columns.zip(@rows.first)] - end - # Returns the last record from the rows collection. - # If the rows collection is empty, returns +nil+. - def last - return nil if @rows.empty? - Hash[@columns.zip(@rows.last)] + def last(n = nil) + n ? hash_rows.last(n) : hash_rows.last end def cast_values(type_overrides = {}) # :nodoc: diff --git a/activerecord/test/cases/result_test.rb b/activerecord/test/cases/result_test.rb index 825aee242393bc4eb36d491c78442b557b6f4bad..4ac2097734af304994da2655d794d19d9508f90a 100644 --- a/activerecord/test/cases/result_test.rb +++ b/activerecord/test/cases/result_test.rb @@ -42,11 +42,35 @@ def result test "first returns first row as a hash" do assert_equal( { "col_1" => "row 1 col 1", "col_2" => "row 1 col 2" }, result.first) + assert_equal [ + { "col_1" => "row 1 col 1", "col_2" => "row 1 col 2" }, + ], result.first(1) + assert_equal [ + { "col_1" => "row 1 col 1", "col_2" => "row 1 col 2" }, + { "col_1" => "row 2 col 1", "col_2" => "row 2 col 2" }, + ], result.first(2) + assert_equal [ + { "col_1" => "row 1 col 1", "col_2" => "row 1 col 2" }, + { "col_1" => "row 2 col 1", "col_2" => "row 2 col 2" }, + { "col_1" => "row 3 col 1", "col_2" => "row 3 col 2" }, + ], result.first(3) end test "last returns last row as a hash" do assert_equal( { "col_1" => "row 3 col 1", "col_2" => "row 3 col 2" }, result.last) + assert_equal [ + { "col_1" => "row 3 col 1", "col_2" => "row 3 col 2" }, + ], result.last(1) + assert_equal [ + { "col_1" => "row 2 col 1", "col_2" => "row 2 col 2" }, + { "col_1" => "row 3 col 1", "col_2" => "row 3 col 2" }, + ], result.last(2) + assert_equal [ + { "col_1" => "row 1 col 1", "col_2" => "row 1 col 2" }, + { "col_1" => "row 2 col 1", "col_2" => "row 2 col 2" }, + { "col_1" => "row 3 col 1", "col_2" => "row 3 col 2" }, + ], result.last(3) end test "each with block returns row hashes" do