开发者

Default conditions for Rails models

开发者 https://www.devze.com 2023-01-14 08:39 出处:网络
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 lis

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消