DEV Community

Discussion on: Why we should avoid default_scope in Rails

Collapse
 
derekjhopper profile image
Derek Hopper

You've touched on it and the references you shared touch on it as well. Anytime I've ever used default_scope in the past I've regretted it over time.

I worked on the same Rails application for 7+ years. A couple default_scope declarations were introduced early in that time frame. I lost count of how many times I had to find ways to get rid of those scopes in a query.

When you first think to use a default_scope, it always seems like, "Oh, this is a good default behavior." Then you start writing code with those assumptions that take advantage of the default scope. Soon, you start having to write code to get around the default scope. After a long enough time, you can't easily go back and change your default scope decision.

A big one for me was a great gem like paranoia (github.com/rubysherpas/paranoia). It typically adds a default scope to hide soft-deleted records. It's a great gem, but for whatever reason, I always found myself fighting it.