From 9a4b946621587547a53fb8f74e04f29ae269042d Mon Sep 17 00:00:00 2001 From: Josh Susser Date: Wed, 23 Mar 2011 21:52:53 -0700 Subject: [PATCH] add #first! to models & relations --- .../lib/active_record/relation/finder_methods.rb | 5 +++++ activerecord/test/cases/finder_test.rb | 12 ++++++++++++ 2 files changed, 17 insertions(+), 0 deletions(-) diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 426000f..c4395aa 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -123,6 +123,11 @@ module ActiveRecord end end + # Same as #first! but raises RecordNotFound if no record is returned + def first!(*args) + self.first(*args) or raise RecordNotFound + end + # A convenience wrapper for find(:last, *args). You can pass in all the # same arguments to this method as you can to find(:last). def last(*args) diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 2e620d8..3f8f161 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -187,6 +187,18 @@ class FinderTest < ActiveRecord::TestCase assert_equal topics(:second).title, Topic.where("title = 'The Second Topic of the day'").first.title end + def test_first_bang_present + assert_nothing_raised do + assert_equal topics(:second), Topic.where("title = 'The Second Topic of the day'").first! + end + end + + def test_first_bang_missing + assert_raises ActiveRecord::RecordNotFound do + Topic.where("title = 'This title does not exist'").first! + end + end + def test_first_failing assert_nil Topic.where("title = 'The Second Topic of the day!'").first end -- 1.7.4.1