Reputation: 465
How to skip default_scope while querying in rails console
E.g
class User < ActiveRecord::Base
default_scope do
where("type != 'guest'")
end
end
Query be like with association
E.g
p = Product.last
p.users.where("...")
I need to skip default_scope for user. I tried p.users.unscoped
, But it fetching all users(not only associated with product)
Upvotes: 2
Views: 3085
Reputation: 101811
Don't use default_scope
. It's going to bite you in the rear.
The only way to remove default_scope
scope is to use unscoped
which as you now have learned removes all scopes - not just the default_scope
.
So p.users.unscoped == User.all.unscoped
.
While you can do:
User.unscoped.where(product: p)
That does not allow you to eager load / include the association to avoid N+1 queries.
Instead of default_scope
you should use explicit scopes:
class User < ApplicationRecord
scope :not_guest, ->{ where.not(type: 'guest') }
end
You should also be careful with the column name type
unless you are using it for Single Table Inheritance (STI). ActiveRecord uses it to determine with class to instanciate from database results it can lead to unexpected bugs. If you want use that column name make sure you set the inheritance column to something else:
class User < ApplicationRecord
self.inheritance_column = :not_type
end
Upvotes: 5