Permalink
Browse files

add #first! and #last! to models & relations

  • Loading branch information...
1 parent 9772de8 commit 5214e73850916de3c9127d35a4ecee0424d364a3 @joshsusser joshsusser committed with tenderlove Mar 24, 2011
Showing with 34 additions and 0 deletions.
  1. +10 −0 activerecord/lib/active_record/relation/finder_methods.rb
  2. +24 −0 activerecord/test/cases/finder_test.rb
@@ -123,6 +123,11 @@ def first(*args)
end
end
+ # Same as #first! but raises RecordNotFound if no record is returned
@skojin
skojin Mar 24, 2011

may be "Same as #first" - without ! ?

@sikachu
sikachu Mar 25, 2011 Ruby on Rails member

Yes, I agree. Must be misspelled ;)

@joshsusser
joshsusser Mar 25, 2011

d'oh! copy/paste strikes again! or I was just too excited!!!!!!!!!!!!!!!!

+ def first!(*args)
+ self.first(*args) or raise RecordNotFound
+ end
+
# A convenience wrapper for <tt>find(:last, *args)</tt>. You can pass in all the
# same arguments to this method as you can to <tt>find(:last)</tt>.
def last(*args)
@@ -137,6 +142,11 @@ def last(*args)
end
end
+ # Same as #last! but raises RecordNotFound if no record is returned
@lukefx
lukefx Mar 25, 2011

Here is the same...#last without '!'.

+ def last!(*args)
+ self.last(*args) or raise RecordNotFound
+ end
+
# A convenience wrapper for <tt>find(:all, *args)</tt>. You can pass in all the
# same arguments to this method as you can to <tt>find(:all)</tt>.
def all(*args)
@@ -191,6 +191,30 @@ def test_first_failing
assert_nil Topic.where("title = 'The Second Topic of the day!'").first
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_last_bang_present
+ assert_nothing_raised do
+ assert_equal topics(:second), Topic.where("title = 'The Second Topic of the day'").last!
+ end
+ end
+
+ def test_last_bang_missing
+ assert_raises ActiveRecord::RecordNotFound do
+ Topic.where("title = 'This title does not exist'").last!
+ end
+ end
+
def test_unexisting_record_exception_handling
assert_raise(ActiveRecord::RecordNotFound) {
Topic.find(1).parent

3 comments on commit 5214e73

@arunagw
Member

Awesome..

@fxn
Member
fxn commented on 5214e73 Mar 24, 2011

Josh would you like to update also the AR querying guide if you find the time? http://guides.rubyonrails.org/active_record_querying.html

@fxn
Member
fxn commented on 5214e73 Mar 25, 2011

Nevermind, the guide has been updated rails/docrails@a094669

Please remember the guides next time, new functionality without proper documentation coverage makes for an incomplete patch, like new functionality without proper test coverage. The patch shouldn't have been accepted as is, the same way it would not have been applied without tests.

Please sign in to comment.