class RuboCop::Cop::Rails::OrderById

This cop 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.

@example

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

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

Constants

MSG
RESTRICT_ON_SEND

Public Instance Methods

on_send(node) click to toggle source
# File lib/rubocop/cop/rails/order_by_id.rb, line 40
def on_send(node)
  add_offense(offense_range(node)) if order_by_id?(node)
end

Private Instance Methods

offense_range(node) click to toggle source
# File lib/rubocop/cop/rails/order_by_id.rb, line 46
def offense_range(node)
  range_between(node.loc.selector.begin_pos, node.source_range.end_pos)
end