1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Add relation.last and relation.reverse_order

This commit is contained in:
Pratik Naik 2009-12-27 19:04:30 +05:30
parent 8957f5db5d
commit d5e98dc859
2 changed files with 40 additions and 1 deletions

View file

@ -44,6 +44,18 @@ module ActiveRecord
create_new_relation(@relation.order(orders)) create_new_relation(@relation.order(orders))
end end
def reverse_order
relation = create_new_relation
relation.instance_variable_set(:@orders, nil)
order_clause = @relation.send(:order_clauses).join(', ')
if order_clause.present?
relation.order(reverse_sql_order(order_clause))
else
relation.order("#{@klass.table_name}.#{@klass.primary_key} DESC")
end
end
def limit(limits) def limit(limits)
create_new_relation(@relation.take(limits)) create_new_relation(@relation.take(limits))
end end
@ -153,13 +165,21 @@ module ActiveRecord
end end
end end
def last
if loaded?
@records.last
else
@last ||= reverse_order.limit(1).to_a[0]
end
end
def loaded? def loaded?
@loaded @loaded
end end
def reload def reload
@loaded = false @loaded = false
@records = @first = nil @records = @first = @last = nil
self self
end end
@ -265,5 +285,18 @@ module ActiveRecord
def where_clause(join_string = "\n\tAND ") def where_clause(join_string = "\n\tAND ")
@relation.send(:where_clauses).join(join_string) @relation.send(:where_clauses).join(join_string)
end end
def reverse_sql_order(order_query)
order_query.to_s.split(/,/).each { |s|
if s.match(/\s(asc|ASC)$/)
s.gsub!(/\s(asc|ASC)$/, ' DESC')
elsif s.match(/\s(desc|DESC)$/)
s.gsub!(/\s(desc|DESC)$/, ' ASC')
else
s.concat(' DESC')
end
}.join(',')
end
end end
end end

View file

@ -309,4 +309,10 @@ class RelationTest < ActiveRecord::TestCase
assert ! fake.exists? assert ! fake.exists?
assert ! fake.exists?(authors(:david).id) assert ! fake.exists?(authors(:david).id)
end end
def test_last
authors = Author.scoped
assert_equal authors(:mary), authors.last
end
end end