1.
Another reason to not use default_scope is when you’re deleting an instance of a model that has a 1 to many relation with the default_scope model
Consider for example:
class User < ActiveRecord::Base
has_many :posts, dependent: :destroy
end
class Post < ActiveRecord::Base
default_scope { where(published: true) }
belongs_to :user
end
Calling user.destroy will delete all the posts that are published, but it won’t delete posts that are unpublished
2.
class Post < ActiveRecord::Base
default_scope { where(published: true) }
end
2.1.1 :004 >
Post.new => #<Post id: nil, title: nil, published: true, created_at: nil, updated_at: nil>
3.
class Post < ActiveRecord::Base
default_scope { where(published: true) }
belongs_to :user
end
class User < ActiveRecord::Base
has_many :posts
end
2.1.1 :002 > User.first.posts.unscoped
Post Load (0.2ms) SELECT "posts".* FROM "posts"