discourse/lib/freedom_patches/pluck_first.rb
Daniel Waterworth 55a1394342 DEV: pluck_first
Doing .pluck(:column).first is a very common pattern in Discourse and in
most cases, a limit cause isn't being added. Instead of adding a limit
clause to all these callsites, this commit adds two new methods to
ActiveRecord::Relation:

pluck_first, equivalent to limit(1).pluck(*columns).first

and pluck_first! which, like other finder methods, raises an exception
when no record is found
2019-10-21 12:08:20 +01:00

20 lines
375 B
Ruby

# frozen_string_literal: true
class ActiveRecord::Relation
def pluck_first(*attributes)
limit(1).pluck(*attributes).first
end
def pluck_first!(*attributes)
items = limit(1).pluck(*attributes)
raise_record_not_found_exception! if items.empty?
items.first
end
end
module ActiveRecord::Querying
delegate(:pluck_first, :pluck_first!, to: :all)
end