Skip to content

Instantly share code, notes, and snippets.

@lmmendes
Created November 4, 2016 12:55
Show Gist options
  • Select an option

  • Save lmmendes/92a6a142ca9cb086aaba9d17545cee6a to your computer and use it in GitHub Desktop.

Select an option

Save lmmendes/92a6a142ca9cb086aaba9d17545cee6a to your computer and use it in GitHub Desktop.
ActiveRecord patch for #last/#first on collection using UUID (PostgreSQL)
require 'active_record'
message = '[ActiveRecord::FinderMethods] Applying patch for #last/#first on collection using UUID'
# rubocop:disable Rails/Output
puts message
# rubocop:enable Rails/Output
# Please read this
# https://github.com/rails/rails/blob/24d82063bcc86a86eb8c8717d74c0c7340e209e6/activerecord/lib/active_record/relation/finder_methods.rb#L479
module ActiveRecord
module FinderMethods
def last(limit = nil)
if limit
if order_values.empty? && primary_key
order(arel_table[:created_at].desc).limit(limit).reverse
else
to_a.last(limit)
end
else
find_last
end
end
def find_nth_with_limit(offset, limit)
if order_values.empty? && primary_key
order(arel_table[:created_at].asc).limit(limit).offset(offset).to_a
else
limit(limit).offset(offset).to_a
end
end
def find_last
if loaded?
@records.last
else
@last ||=
if limit_value
to_a.last
else
order(arel_table[:created_at].desc).limit(1).to_a.first
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment