Class: RuboCop::Cop::Rails::SkipsModelValidations

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

Overview

Checks for the use of methods which skip validations which are listed in guides.rubyonrails.org/active_record_validations.html#skipping-validations

Methods may be ignored from this rule by configuring a ‘AllowedMethods`.

Examples:

# bad
Article.first.decrement!(:view_count)
DiscussionBoard.decrement_counter(:post_count, 5)
Article.first.increment!(:view_count)
DiscussionBoard.increment_counter(:post_count, 5)
person.toggle :active
product.touch
Billing.update_all("category = 'authorized', author = 'David'")
user.update_attribute(:website, 'example.com')
user.update_columns(last_request_at: Time.current)
Post.update_counters 5, comment_count: -1, action_count: 1

# good
user.update(website: 'example.com')
FileUtils.touch('file')

AllowedMethods: [“touch”]

# bad
DiscussionBoard.decrement_counter(:post_count, 5)
DiscussionBoard.increment_counter(:post_count, 5)
person.toggle :active

# good
user.touch

Constant Summary collapse

MSG =
'Avoid using `%<method>s` because it skips validations.'
METHODS_WITH_ARGUMENTS =
%w[decrement!
decrement_counter
increment!
increment_counter
insert
insert!
insert_all
insert_all!
toggle!
update_all
update_attribute
update_column
update_columns
update_counters
upsert
upsert_all].freeze

Instance Method Summary collapse

Constructor Details

#initializeSkipsModelValidations

Returns a new instance of SkipsModelValidations.



86
87
88
89
90
# File 'lib/rubocop/cop/rails/skips_model_validations.rb', line 86

def initialize(*)
  super
  @displayed_allowed_warning = false
  @displayed_forbidden_warning = false
end

Instance Method Details

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



75
76
77
78
79
80
81
82
83
# File 'lib/rubocop/cop/rails/skips_model_validations.rb', line 75

def on_send(node)
  return if allowed_methods.include?(node.method_name.to_s)
  return unless forbidden_methods.include?(node.method_name.to_s)
  return if allowed_method?(node)
  return if good_touch?(node)
  return if good_insert?(node)

  add_offense(node.loc.selector, message: message(node))
end