Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix for multiple default_scope all_queries options
In our use case - we have a base model that has a default scope that we want enabled for all queries, ex: ```ruby class Developer < ApplicationRecord default_scope -> { where(firm_id: Current.firm_id) }, all_queries: true end ``` We're also leveraging a module that will add a default scope to only find soft-deleted records. ```ruby module SoftDeletable extend ActiveSupport::Concern included do default_scope { where(deleted_at: nil) } end ``` Through this, we've found that when using default scopes in combination, *specifically in the use case where the _non_ all queries scope is declared first*, that we would get an error when calling `.update`: ```ruby class Developer < ApplicationRecord include SoftDeletable default_scope -> { where(firm_id: Current.firm_id) }, all_queries: true ``` ```ruby Current.firm_id = 5 developer = Developer.new(name: "Steve") developer.update(name: "Stephen") NoMethodError: undefined method `where' for nil:NilClass ``` In digging into the code, this was due to there not being an `else` case for the `inject` used to combine `default_scopes` together (`inject` uses the return value of the block as the memoizer). Without the `else` case, if the block returned `nil`, `nil` was passed to the evaluation of the next `default_scope`. This commit adds the `else`, and also makes a minor adjustment in variable naming (`default_scope` to `combined_scope`) in an effort to add a little more readability, as we're iterating over an array of default scopes, but what we're building is _the_ default scope to be used in the query, etc. Co-authored-by: Will Cosgrove <will@cosgrove.email>
- Loading branch information