Ruby on Rails: how to override default_scope – a better approach

Ever used default_scope in RoR? Ever regretted you had ever read about this feature after you wrote tons of code and later realized you can’t access the records you need in a convenient way when necessary? Try googling “how to override default_scope” and you will find tons of advices how to do it with model.send(:with_exclusive_scope) { super }, but no real way how to cancel it completely for a model when you really need it (like in tests for instance). Here is a simple solution and a few advices regarding this misfeature:


Say, you have
class Foo < ActiveRecord::Base default_scope :conditions => { "0" }
end

And at some place in your code you need to cancel the default_scope. Here is the code:
RecurringDonationSchedule.send( :default_scope, {} )

default_scope is just a protected method of ActiveRecord::Base, so you can call it with send and fix your previous mistake (which is using default_scope in such a manner).

I guess you already realized that default_scope is a bad idea in many cases, even though named_scope is a brilliant idea. Still, using default_scope could be a good idea if you use it for sorting, just don’t use it for filtering. I hope they will remove this misfeature in the future releases of Rails.

Leave a Reply