Sha256: e8c540a8177d1fd9d10bbfa7bb8124c9c91742c3debf5f38d5bb011c09a866be

Contents?: true

Size: 986 Bytes

Versions: 2

Compression:

Stored size: 986 Bytes

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Rails
      # This cop 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.
      #
      # @example
      #   # bad
      #   Post.where(user_id: User.active.pluck(:id))
      #
      #   # good
      #   Post.where(user_id: User.active.select(:id))
      #
      class PluckInWhere < Cop
        include ActiveRecordHelper

        MSG = 'Use `select` instead of `pluck` within `where` query method.'

        def on_send(node)
          add_offense(node, location: :selector) if node.method?(:pluck) && in_where?(node)
        end

        def autocorrect(node)
          lambda do |corrector|
            corrector.replace(node.loc.selector, 'select')
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rubocop-rails-2.7.1 lib/rubocop/cop/rails/pluck_in_where.rb
rubocop-rails-2.7.0 lib/rubocop/cop/rails/pluck_in_where.rb