mirror of
https://github.com/discourse/discourse.git
synced 2025-02-25 18:55:32 -06:00
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
This commit is contained in:
19
lib/freedom_patches/pluck_first.rb
Normal file
19
lib/freedom_patches/pluck_first.rb
Normal file
@@ -0,0 +1,19 @@
|
||||
# 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
|
||||
Reference in New Issue
Block a user