views:

32

answers:

1
+2  Q: 

Redefining :all

I have users in my system that can elect to 'hibernate', at which point they can remove themselves and all of their associated records entirely from the system. I have queries all over my site that search within the User table and its associated tables (separated by as many as 5 intermediate tables), and none explicitly test whether the user is hibernating or not.

Is there a way to redefine the User set to non-hibernating users only, so all my current queries will work without being changed individually?

How can I most elegantly accomplish what I'm trying to do?

+4  A: 

This is typically done with default scopes. Read all about them

Code from Ryan's site:

class User < ActiveRecord::Base
  default_scope :hibernate => false
end

# get all non-hibernating users
@users = User.all

# get all users, not just non-hibernating (break out of default scope)
@users = User.with_exclusive_scope { find(:all) }  #=> "SELECT * FROM `users`
Jesse Wolgamott
+1 This came in just as I was typing in the same thing :) The only thing I'd add is that you can use `User.unscoped` instead of the `with_exclusive_scope` block if you are using Rails 3
edgerunner
This was so good it made me vote to delete my own answer!
zetetic
Excellent! Thank you for coming up with this solution!
sscirrus