Class: RuboCop::Cop::DevDoc::Migration::AvoidUpdateColumn

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/dev_doc/migration/avoid_update_column.rb

Overview

Avoid ‘update_column`, `update_columns`, and `update_all` in migrations.

## Rationale Avoid bypassing validation unless absolutely necessary. These methods skip validations and callbacks, which hides data integrity issues rather than surfacing them.

Even in migrations, check the code to see if there is any blatant reason why existing records may be invalid. If there is, fix those records first rather than bypassing validation.

 Bypasses validation  hides data integrity issues
Faq.where(purpose: nil).update_all(purpose: :intro)

✔️ Runs validation  surfaces problems early
Faq.where(purpose: nil).find_each do |faq|
  faq.purpose = :intro
  faq.save!
end

NOTE: The broader principle (“avoid bypassing validation”) also covers things this cop does not catch, e.g. ‘save(validate: false)`, `insert_all`, `upsert_all`, `delete_all`. Apply the same judgement to those patterns.

Examples:

# bad
Faq.where(purpose: nil).update_all(purpose: :intro)

# bad
user.update_column(:status, 'active')

# good
Faq.where(purpose: nil).find_each do |faq|
  faq.purpose = :intro
  faq.save!
end

Constant Summary collapse

MSG =
'Avoid `%<method>s` in migrations; it bypasses validations. Use `save!` instead.'.freeze
RESTRICT_ON_SEND =
%i[update_column update_columns update_all].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



46
47
48
# File 'lib/rubocop/cop/dev_doc/migration/avoid_update_column.rb', line 46

def on_send(node)
  add_offense(node.loc.selector, message: format(MSG, method: node.method_name))
end