class RuboCop::Cop::Rails::RedundantActiveRecordAllMethod
ActiveSupport::TimeZone.all.first
ActionMailer::Preview.all.first
# good
@example AllowedReceivers: [‘ActionMailer::Preview’, ‘ActiveSupport::TimeZone’] (default)
user.articles.order(:created_at)
users.where(id: ids)
User.order(:created_at)
User.find(id)
# good
user.articles.all.order(:created_at)
users.all.where(id: ids)
User.all.order(:created_at)
User.all.find(id)
# bad
@example
This cop is unsafe for autocorrection if the receiver for ‘all` is not an Active Record object.
@safety
which can affect their behavior.
from `ActiveRecord::Relation` to `ActiveRecord::Associations::CollectionProxy`,
This is because omitting `all` from an association changes the methods
It will ignore cases where the receiver is an association (e.g., `user.articles.all.delete_all`).
For the methods `delete_all` and `destroy_all`, this cop will only check cases where the receiver is a model.
Detect redundant `all` used as a receiver for Active Record query methods.
def offense_range(node)
def offense_range(node) range_between(node.loc.selector.begin_pos, node.source_range.end_pos) end
def on_send(node)
def on_send(node) return unless followed_by_query_method?(node.parent) return if possible_enumerable_block_method?(node) || sensitive_association_method?(node) return if node.receiver ? allowed_receiver?(node.receiver) : !inherit_active_record_base?(node) range_of_all_method = offense_range(node) add_offense(range_of_all_method) do |collector| collector.remove(range_of_all_method) collector.remove(node.parent.loc.dot) end end
def possible_enumerable_block_method?(node)
def possible_enumerable_block_method?(node) parent = node.parent return false unless POSSIBLE_ENUMERABLE_BLOCK_METHODS.include?(parent.method_name) parent.block_literal? || parent.first_argument&.block_pass_type? end
def sensitive_association_method?(node)
def sensitive_association_method?(node) !node.receiver&.const_type? && SENSITIVE_METHODS_ON_ASSOCIATION.include?(node.parent.method_name) end