DEV Community

loading...

Rails - Run Default Scope on All queries

Sohair Ahmad
I am rails developer
・1 min read

In a recent release candidate of Rails 6.1 (RC2) I have found a small but useful change in the active record library.

Consider a multi-tenant rails application, where everything was under the umbrella of the Organization.

default_scope used to run on all select and insert queries.

Previously:

class User < ApplicationRecord
  default_scope -> { where(organization_id: Current.organization.id) }
end
Enter fullscreen mode Exit fullscreen mode

Now, Rails has the ability to run this default_scope on select, insert, delete and update queries by just adding all_queries: true

class User < ApplicationRecord
  default_scope -> { where(organization_id: Current.organization.id) }, all_queries: true
end
Enter fullscreen mode Exit fullscreen mode

Discussion (0)