Class: RuboCop::Cop::Rails::OptionalBelongsTo

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

Overview

Requires belongs_to to declare optional: true. The 4Shark convention is to skip Rails' automatic presence/existence validation (a SELECT per record) and validate presence manually with validates :x_id, presence: true.

Scoped to app/models via the Include config.

Examples:

# bad
belongs_to :user

# good
belongs_to :user, optional: true

Constant Summary collapse

MSG =
'Declare `belongs_to` with `optional: true` and validate presence manually.'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.default_configurationObject



24
25
26
27
28
# File 'lib/rubocop/cop/rails/optional_belongs_to.rb', line 24

def self.default_configuration
  super.merge(
    'Include' => ['app/models/**/*.rb']
  )
end

Instance Method Details

#on_send(node) ⇒ Object



30
31
32
33
34
35
# File 'lib/rubocop/cop/rails/optional_belongs_to.rb', line 30

def on_send(node)
  return unless node.method?(:belongs_to)
  return if optional_true?(node)

  add_offense(node.loc.selector)
end