Class: RuboCop::Cop::Rails::PluckInWhere

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
ConfigurableEnforcedStyle, ActiveRecordHelper
Defined in:
lib/rubocop/cop/rails/pluck_in_where.rb

Overview

Identifies places where ‘pluck` is used in `where` query methods and can be replaced with `select`.

Since ‘pluck` is an eager method and hits the database immediately, using `select` helps to avoid additional database queries.

This cop has two different enforcement modes. When the ‘EnforcedStyle` is `conservative` (the default) then only calls to `pluck` on a constant (i.e. a model class) in the `where` is used as offenses.

Examples:

# bad
Post.where(user_id: User.active.pluck(:id))

# good
Post.where(user_id: User.active.select(:id))
Post.where(user_id: active_users.select(:id))

EnforcedStyle: conservative (default)

# good
Post.where(user_id: active_users.pluck(:id))

EnforcedStyle: aggressive

# bad
Post.where(user_id: active_users.pluck(:id))

Constant Summary collapse

MSG =
'Use `select` instead of `pluck` within `where` query method.'
RESTRICT_ON_SEND =
%i[pluck].freeze

Constants included from ActiveRecordHelper

ActiveRecordHelper::WHERE_METHODS

Instance Method Summary collapse

Methods included from ActiveRecordHelper

#external_dependency_checksum, #foreign_key_of, #in_where?, #inherit_active_record_base?, #polymorphic?, #resolve_relation_into_column, #schema, #table_name

Instance Method Details

#on_send(node) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/rubocop/cop/rails/pluck_in_where.rb', line 46

def on_send(node)
  return unless in_where?(node)
  return if style == :conservative && !root_receiver(node)&.const_type?

  range = node.loc.selector

  add_offense(range) do |corrector|
    corrector.replace(range, 'select')
  end
end