Reputation: 1
How does the default scope work?
For example, I have in my model:
default_scope -> { includes(:translations) }
This is my model:
class MyModel
default_scope -> { includes(:translations) }
has_many: translations
end
I know about that default scope can do some default job, for example sort by column.
But how it works with include
?
Upvotes: 0
Views: 106
Reputation: 2791
The method includes
was designed to solve N + 1 query problem. For example, if you have a model:
class MyModel < ApplicationRecord
has_many :translations
end
Then this code
MyModel.limit(50).each do |model|
model.translations.each do |translation|
# ...
end
end
generates 51 queries to your database: one query to fetch 50 records from my_models
table, and 50 queries to fetch translations
for each of these models. This affects the performance of the application dramatically.
To fix it the code could be rewritten as:
MyModel.includes(:translations).limit(50).each do |model|
...
With includes
Rails generates only 2 SQL query. First one fetches 50 my_models
records, and second query fetches translations
for those my_models
.
Having default_scope -> { includes(:translations) }
just let you skip writing includes(:translations)
in the situations described above. Even if you write
MyModel.limit(50).each do |model|
...
Rails will do 2 queries since translations are included by default scope.
I need to add that default_scope has some non-obvious pitfalls, and it's not recommended by some developers.
Upvotes: 2