Reputation: 263
I have a User model where I have a default_scope to get all users which are still active. Along with the default scope, I also have named scopes. My User model looks something like:
default_scope { where(status: "active") }
scope :location, -> (location) { where(location: location) }
For a specific query I need to bypass the default_scope and use location scope. I know I can use unscoped to bypass a scope but as per my understanding, unscope will bypass all the scopes.
How can I do it?
Upvotes: 0
Views: 81
Reputation: 1309
You can bypass the default scope and then apply your custom scope, like this:
User.unscoped.location('London')
You do need to do it in this order, though, otherwise (as you say) the unscoped
call will remove the scopes that were called before it.
Also, consider not using a default scope in this way. If you ever want (as in this example) to retrieve inactive users, you'll have problems. You're probably better having an active
scope (and perhaps an inactive
scope) that you can call when you want that limitation and not call when you don't! That way, your code will be much clearer about the records you expect to get back.
User.active.location('London')
User.inactive.location('London')
User.all.location('London')
etc.
Personally, I would only use a default scope for sorting records into date order so first
and last
return useful results (helpful when using uuids because, unlike integer ids, the records are in no particular order). But some people would disagree even with that!
Upvotes: 1