aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/relation/finder_methods.rb
diff options
context:
space:
mode:
authorMarcelo Silveira <marcelo@mhfs.com.br>2012-04-26 21:03:25 -0300
committerMarcelo Silveira <marcelo@mhfs.com.br>2012-05-02 21:25:40 -0300
commit1379375f93c53d4c49fa8592b6117c3ade263f2e (patch)
treea39b16aa181cfd00b0ca253873f0dd1bcb7f29ff /activerecord/lib/active_record/relation/finder_methods.rb
parent489166e114ba3af54b1f2081027cd44078d32bbc (diff)
downloadrails-1379375f93c53d4c49fa8592b6117c3ade263f2e.tar.gz
rails-1379375f93c53d4c49fa8592b6117c3ade263f2e.tar.bz2
rails-1379375f93c53d4c49fa8592b6117c3ade263f2e.zip
Introducing `take` as a replacement to the old behavior of `first`
Diffstat (limited to 'activerecord/lib/active_record/relation/finder_methods.rb')
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb27
1 files changed, 27 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 4a41f1ea8b..7af69d3483 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -60,6 +60,25 @@ module ActiveRecord
where(*args).first!
end
+ # Gives a record (or N records if a parameter is supplied) without any implied
+ # order. The order will depend on the database implementation.
+ # If an order is supplied it will be respected.
+ #
+ # Examples:
+ #
+ # Person.take # returns an object fetched by SELECT * FROM people
+ # Person.take(5) # returns 5 objects fetched by SELECT * FROM people LIMIT 5
+ # Person.where(["name LIKE '%?'", name]).take
+ def take(limit = nil)
+ limit ? limit(limit).to_a : find_take
+ end
+
+ # Same as +take+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
+ # is found. Note that <tt>take!</tt> accepts no arguments.
+ def take!
+ take or raise RecordNotFound
+ end
+
# Find the first record (or first N records if a parameter is supplied).
# If no order is defined it will order by primary key.
#
@@ -329,6 +348,14 @@ module ActiveRecord
end
end
+ def find_take
+ if loaded?
+ @records.take(1)[0]
+ else
+ @take ||= limit(1).to_a[0]
+ end
+ end
+
def find_first
if loaded?
@records.first