Skip to content

Refactor default_scope from Post model #42

@kanejamison

Description

@kanejamison

Description

The Post model currently uses default_scope { order(created_at: :desc) } which is a documented Rails anti-pattern. This affects ALL queries on the Post model globally, including associations, counts, and eager loading.

Problems this causes

  1. Developers have to constantly use .unscoped to work around it (we already see this in the test suite)
  2. Makes debugging difficult - queries don't behave as expected
  3. Breaks Rails semantics for first and last
  4. Can cause unexpected N+1 queries when used in associations
  5. Affects third-party gems that query the Post model

Pros of refactoring

  • Predictable query behavior
  • Fewer surprises for developers using the gem
  • Follows Rails best practices and official documentation warnings
  • Easier debugging
  • Better performance in some cases

Cons of refactoring

  • Need to explicitly order queries in controllers/scopes
  • Users might forget to order and get inconsistent results
  • Small breaking change if anyone is relying on the default order

Recommended approach

Replace with a named scope as the conventional entry point:

scope :latest, -> { order(created_at: :desc) }
scope :oldest, -> { order(created_at: :asc) }

And update Collection concern to use explicit ordering (which it already does via apply_ordering).

References

  • lib/bunko/models/post_methods.rb:32

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions