Resume and bio of the author Couple of articles related to my hobby - robotics
My impressions about immigration to Australia. In Russian only. Recipes for everyday problems solving
Linux-related posts Windows-related posts
Software-related posts A lot of info about hardware
Different tools you might find useful Posts about various web technologies
Everything that doesn't fit the rest of the menu RSS feed for this blog

Tag Cloud



Andrey Mikhalchuk’s Blog

Technoblog about life

Jul 2, 2010 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" }

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.

This post is published in Other, Web.

No comments

No comments so far

Leave a Reply

You must be logged in to post a comment.

Site Map (c) Andrey Mikhalchuk, 2005-2008