Class: RuboCop::Cop::Rails::OrderById

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

Overview

Checks for places where ordering by ‘id` column is used.

Don’t use the ‘id` column for ordering. The sequence of ids is not guaranteed to be in any particular order, despite often (incidentally) being chronological. Use a timestamp column to order chronologically. As a bonus the intent is clearer.

NOTE: Make sure the changed order column does not introduce performance bottlenecks and appropriate database indexes are added.

Examples:

# bad
scope :chronological, -> { order(id: :asc) }
scope :chronological, -> { order(primary_key => :asc) }

# good
scope :chronological, -> { order(created_at: :asc) }

Constant Summary collapse

MSG =
'Do not use the `id` column for ordering. Use a timestamp column to order chronologically.'
RESTRICT_ON_SEND =
%i[order].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



39
40
41
# File 'lib/rubocop/cop/rails/order_by_id.rb', line 39

def on_send(node)
  add_offense(offense_range(node)) if order_by_id?(node)
end