Class: RuboCop::Cop::DevDoc::Rails::StrongParametersExpect

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/dev_doc/rails/strong_parameters_expect.rb

Overview

Flag params.require(:foo).permit(...) and the reverse form params.permit(foo: ...).require(:foo) — use params.expect(foo: [...]) instead.

Rationale

The upstream Rails/StrongParametersExpect autocorrects two distinct patterns: the hash-form rewrite (require.permitexpect) and the scalar form (params[:id] inside find-method chains). The scalar form fires false positives on optional query params (e.g. params[:status]&.to_sym || :draft) and forces scattered per-line disables — the typical workaround is to disable the upstream cop entirely, losing the hash-form benefit too.

This cop targets only the hash-form rewrite, so projects can keep Rails/StrongParametersExpect: Enabled: false and still enforce the safe params.expect pattern.

params.expect raises ActionController::ParameterMissing for scalar values where permit would silently return nil, and it makes the permitted-attribute shape explicit in one call.

Patterns detected

 require  permit chain
params.require(:user).permit(:name, :email)

 permit  require chain (less common)
params.permit(user: %i[name email]).require(:user)

✔️
params.expect(user: [:name, :email])

Not flagged

Scalar params[:foo] in any context — leave that to per-project decision or the upstream cop.

Examples:

# bad
params.require(:user).permit(:name, :email)

# bad
params.require(:user).permit(:name, profile_attributes: [:bio])

# bad
params.permit(user: %i[name email]).require(:user)

# good
params.expect(user: [:name, :email])

# good
params.expect(user: [:name, { profile_attributes: [:bio] }])

Constant Summary collapse

MSG_REQUIRE_PERMIT =
'Use `params.expect(%<key>s: [...])` instead of ' \
'`params.require(:%<key>s).permit(...)`.'
MSG_PERMIT_REQUIRE =
'Use `params.expect(%<key>s: ...)` instead of ' \
'`params.permit(%<key>s: ...).require(:%<key>s)`.'
RESTRICT_ON_SEND =
%i[permit require].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



66
67
68
69
# File 'lib/rubocop/cop/dev_doc/rails/strong_parameters_expect.rb', line 66

def on_send(node)
  check_require_permit(node) if node.method_name == :permit
  check_permit_require(node) if node.method_name == :require
end