Class: RuboCop::Cop::Rails::FindById

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/rails/find_by_id.rb

Overview

Enforces that ‘ActiveRecord#find` is used instead of `where.take!`, `find_by!`, and `find_by_id!` to retrieve a single record by primary key when you expect it to be found.

Examples:

# bad
User.where(id: id).take!
User.find_by_id!(id)
User.find_by!(id: id)

# good
User.find(id)

Constant Summary collapse

MSG =
'Use `%<good_method>s` instead of `%<bad_method>s`.'
RESTRICT_ON_SEND =
%i[take! find_by_id! find_by!].freeze

Instance Method Summary collapse

Instance Method Details

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



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

def on_send(node)
  where_take?(node) do |where, id_value|
    range = where_take_offense_range(node, where)

    register_offense(range, id_value)
  end

  find_by?(node) do |id_value|
    range = find_by_offense_range(node)

    register_offense(range, id_value)
  end
end