New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
default_scope
side effect when using all_queries: true
#46731
Comments
This functionality was added in #40805. But I think you are correct, that only the Here is a failing test: def test_default_scope_with_all_queries_runs_on_reload_but_default_scope_without_all_queries_does_not
Mentor.create!
dev = DeveloperWithIncludedMentorDefaultScopeNotAllQueriesAndDefaultScopeFirmWithAllQueries.create!(name: "Eileen")
reload_sql = capture_sql { dev.reload }.first
assert_no_match(/mentor_id/, reload_sql)
assert_match(/firm_id/, create_sql)
end |
Could you see if #46742 fixes the issue for you? |
Yup, that does make the |
defaut_scope
side effect when using all_queries: true
default_scope
side effect when using all_queries: true
Description
There's some inconsistency in the behaviour of default_scopes.
As many scopes can be configured to an AR model and none of them will be applied when reloading a record. Now if there's a single one with
all_queries: true
then all of them get appliedRef:
https://github.com/rails/rails/blob/main/activerecord/lib/active_record/persistence.rb#L1048
https://github.com/rails/rails/blob/main/activerecord/lib/active_record/persistence.rb#L1138
rails/activerecord/lib/active_record/scoping/default.rb
Line 64 in bd7b6de
Steps to reproduce
1 - Add a
default_scope(all_queries: false { where("1=1") }
to an AR model2 - create a record, query, and reload it - the scope is not applied in the reload query
3 - Add another default scope, now all_queries: true
default_scope(all_queries: true { where("2=2") }
4 - repeat step 2 and inspect the query - it will include both scopes
Expected behavior
Adding a
default_scope
to an ActiveRecord model should not affect how otherdefault_scope
behave when reloading a record.I would expect consistency in the behaviour of the query, so either:
all_queries
default scopes get applied to the query upon reloading the modeldefault_scope
gets applied upon reloading the model (as I'm not sure why such scopes are applied at all in thereload
operation)Actual behavior
A model may define several
all_queries: false
default_scopes and none of them will be applied upon reloading a record.If a single
all_queries: true
default_scope is added to such model, then all default_scopes get appliedSystem configuration
Rails version:
(tested on)
7.0.3.1
and onmain
Ruby version:
(tested on)
3.0.5
and3.1.2
The text was updated successfully, but these errors were encountered: