在Rails中覆盖default_scope [英] Overriding default_scope in Rails

查看:56
本文介绍了在Rails中覆盖default_scope的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Post.rb模型中,我有default_scope :conditions => {:deleted => 'false'}

In my Post.rb model, I have default_scope :conditions => {:deleted => 'false'}

但是,如果我尝试运行Post.find(:all, :conditions => "deleted='false'"),它将不会返回任何内容.好像default_scope优先于所有内容.

But if I try to run Post.find(:all, :conditions => "deleted='false'"), it won't return anything. It's as if the default_scope takes precedence over everything.

我想要它,这样当我执行Post.find()时它不会返回已删除的帖子,但是如果需要,我也希望能够访问它们.在查询或Rails模型中需要更改什么?

I want it so that when I do Post.find() it doesn't return deleted posts, but I'd also like to be able to access them if I need to. What needs to be changed in either my query or my Rails model?

谢谢.

推荐答案

with_exclusive_scopeprotected,因此您必须创建一个类方法:

with_exclusive_scope is protected, so you have to create a class method:

def self.include_deleted_in
  Event.with_exclusive_scope { yield }
end

然后在您的控制器调用中

then in your controller call

Post.include_deleted_in { Post.find(:all) }

这篇关于在Rails中覆盖default_scope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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