默认情况Rails的模型 [英] Default conditions for Rails models

查看:263
本文介绍了默认情况Rails的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,其中有一个叫做场删除,这是用来纪念那些删除的项目。

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

所以,通常我只会想查询那些具有删除= FALSE 的项目,并在某些特殊情况下,列出这些已删除项目的恢复。

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}

有没有更好的方式来做到这一点,这样当我做 Item.other_named_scope ,我能找到所有这些未删除的项目?

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?

推荐答案

您可以使用default_scope这一点。

You can use default_scope for this.

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

现在所有查询到发布模式将在有效的帖子。当你想覆盖此行为使用 with_exclusive_scope

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

参考:

链接1

买者

在default_scope影响到每一个取景器调用。它应谨慎使用,并与的不必要的副作用充分认识。

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

这篇关于默认情况Rails的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆