Class: RuboCop::Cop::Gusto::PluckOnSelect

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/gusto/pluck_on_select.rb

Overview

Do not use .pluck on .select.

.select returns an ActiveRecord relation with only the selected columns marked for retrieval. .pluck returns an array of column values. When chained, .pluck is unaware of any directive passed to .select (e.g. column aliases or a DISTINCT clause), which can cause unexpected behavior.

Examples:

Redundant select

# bad
User.select(:id).pluck(:id)

# good
User.pluck(:id)

Column alias: .pluck raises "Unknown column" because it ignores the alias

# bad
User.select('id AS id2').pluck('id2')

# good: use .select alone if you need the alias
User.select(:id, 'id AS id2')

# good: use .pluck alone if you don't need the alias
User.pluck(:id)

DISTINCT: .pluck loads all rows, ignoring the DISTINCT from .select

# bad
User.select('DISTINCT email').pluck(:email)

# good
User.distinct.pluck(:email)

Constant Summary collapse

RESTRICT_ON_SEND =
%i(pluck).freeze
MSG =
"Do not use `.pluck` on `.select`."

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object Also known as: on_csend



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/rubocop/cop/gusto/pluck_on_select.rb', line 41

def on_send(node)
  return unless node.receiver

  receiver_node = node.receiver
  while receiver_node
    if receiver_node.call_type? && receiver_node.method?(:select)
      add_offense(node)
      break
    end
    receiver_node = receiver_node.receiver
  end
end