Class: RuboCop::Cop::Rails::UnscopedOverNonModelConstant

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/rails/unscoped_over_non_model_constant.rb

Overview

Identifies calls to ‘unscoped` over non model constants. This can be an issue because `unscoped` removes all scopes defined before. Calling it directly to the model, it can be considered as safe because only `default_scope` will be removed, which is the main reason to use `unscoped` statement.

Examples:

# bad
User.where(trashed: true).unscoped.first
User.trashed.unscoped.joins(:posts).where(posts: { trashed: true, title: 'Rails' }).first
User.joins(:posts).where(posts: { trashed: true, title: 'Rails' }).unscoped.first

# good
User.unscoped.where(trashed: true)
User.unscoped.joins(:posts).where(posts: { trashed: true, title: 'Rails' })

Constant Summary collapse

MSG =
'Prevent usage of `unscoped` over non model constants.'
RESTRICT_ON_SEND =
i[unscoped].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/rubocop/cop/rails/unscoped_over_non_model_constant.rb', line 28

def on_send(node)
  return unless node.receiver
  return if node.receiver.respond_to?(:method_name) && _allowed_methods.include?(node.receiver.method_name.to_s)

  unscoped_call?(node) do
    next unless _unscoped_on_non_const?(node)

    range = node.loc.selector.with(end_pos: node.loc.expression.end_pos)

    add_offense(range)
  end
end