Skip to main content

Avoid Rails Default Scopes

ยท One min read

A common mistake when beginning to use Rails is sprinkling all the models with default scopes specifying order.

class Foo < ActiveRecord::Base
default_scope { order(name: :asc) }
end

This will add order by's to query even when the order does not matter.

Foo.find(123)

Executes the following

SELECT  "foos".* FROM "foos" WHERE "foos"."id" = 123  ORDER BY "foos"."name" ASC LIMIT 1

The best use-case I've found with default scopes is scoping a model to the current tenant in a multi-tenant environment.

However, even that is questionable, as one could just do current_tenant.foos instead. In the controller, specify a scope allowing fetching to be scoped to tenant.

def foo_scope
current_tenant.foos
end