mirror of
https://github.com/discourse/discourse.git
synced 2024-11-22 22:21:55 +08:00
55a1394342
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
20 lines
375 B
Ruby
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
|