diff options
author | Benjamin Quorning <benjamin@quorning.net> | 2016-06-24 09:50:41 +0200 |
---|---|---|
committer | Benjamin Quorning <benjamin@quorning.net> | 2016-06-24 11:43:22 +0200 |
commit | e292ce8a4f4559aed6faef58e03ced649513cf2f (patch) | |
tree | 6234a32a03ad1148a0e565570885dd055aebb95f /activerecord | |
parent | 006ea8171dc68fad2b8e7b57b08cab5245fd9476 (diff) | |
download | rails-e292ce8a4f4559aed6faef58e03ced649513cf2f.tar.gz rails-e292ce8a4f4559aed6faef58e03ced649513cf2f.tar.bz2 rails-e292ce8a4f4559aed6faef58e03ced649513cf2f.zip |
Add ActiveRecord::Result#first
When you only need the first element of a result set, you shouldn't need to
instantiate all of hash_rows.
Diffstat (limited to 'activerecord')
-rw-r--r-- | activerecord/lib/active_record/result.rb | 5 | ||||
-rw-r--r-- | activerecord/test/cases/result_test.rb | 5 |
2 files changed, 10 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb index 8e6cd6c82f..f45f664efe 100644 --- a/activerecord/lib/active_record/result.rb +++ b/activerecord/lib/active_record/result.rb @@ -75,6 +75,11 @@ module ActiveRecord hash_rows[idx] end + def first + return nil if @rows.empty? + Hash[@columns.zip(@rows.first)] + end + def last hash_rows.last end diff --git a/activerecord/test/cases/result_test.rb b/activerecord/test/cases/result_test.rb index dec01dfa76..565593c500 100644 --- a/activerecord/test/cases/result_test.rb +++ b/activerecord/test/cases/result_test.rb @@ -22,6 +22,11 @@ module ActiveRecord ], result.to_hash end + 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) + end + test "each with block returns row hashes" do result.each do |row| assert_equal ['col_1', 'col_2'], row.keys |