Skip to content

Commit

Permalink
Refactored ActiveRecord first method to get rid of duplication.
Browse files Browse the repository at this point in the history
  • Loading branch information
dmitry committed Jun 9, 2013
1 parent 7a32c63 commit d5450a6
Showing 1 changed file with 10 additions and 11 deletions.
21 changes: 10 additions & 11 deletions activerecord/lib/active_record/relation/finder_methods.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -81,11 +81,7 @@ def take!
# Person.first(3) # returns the first three objects fetched by SELECT * FROM people LIMIT 3 # Person.first(3) # returns the first three objects fetched by SELECT * FROM people LIMIT 3
def first(limit = nil) def first(limit = nil)
if limit if limit
if order_values.empty? && primary_key find_first_records(order_values, limit)
order(arel_table[primary_key].asc).limit(limit).to_a
else
limit(limit).to_a
end
else else
find_first find_first
end end
Expand Down Expand Up @@ -307,12 +303,15 @@ def find_first
if loaded? if loaded?
@records.first @records.first
else else
@first ||= @first ||= find_first_records(with_default_scope.order_values, 1).first
if with_default_scope.order_values.empty? && primary_key end
order(arel_table[primary_key].asc).limit(1).to_a.first end
else
limit(1).to_a.first def find_first_records(order_values, limit)
end if order_values.empty? && primary_key
order(arel_table[primary_key].asc).limit(limit).to_a
else
limit(limit).to_a
end end
end end


Expand Down

0 comments on commit d5450a6

Please sign in to comment.