views:

24

answers:

1

I have a model which has a field called deleted, which is used to mark those deleted items.

So normally I would just want to query those having deleted = false items, and in some special cases to list those deleted items for restoring.

Is it possible to do that? What I could do now is just using a named scope having :conditions => {:deleted => false}

Is there a better way to do it so that When I do Item.other_named_scope, I could find all those not-deleted items?

+2  A: 

You can use default_scope for this.

class Post
  default_scope :conditions => {:deleted => false}
end

Now all queries to the Post model will be on ACTIVE posts. When you want to override this behavior use with_exclusive_scope:

Post.with_exclusive_scope{ find_all_by_deleted(true) } #returns deleted records

Reference:

Link 1

Caveat

The default_scope affects every finder call. It should be used with care and with full awareness of the unwanted side-effects.

KandadaBoggu