Default conditions for Rails models

青春壹個敷衍的年華 提交于 2019-12-11 03:38:57

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/3605914/default-conditions-for-rails-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!