如何在 Rails 3 中取消关联记录的范围 [英] How to unscope an associated record in Rails 3

查看:44
本文介绍了如何在 Rails 3 中取消关联记录的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在 Rails 中正确设置作用域.

I'm having some trouble getting scoping to work correctly in rails.

我的模型:

class User < ActiveRecord::Base
  default_scope :conditions => 'users.deleted_at IS NULL'


class Feed < ActiveRecord::Base
  belongs_to :user, :foreign_key => :author_id

当我调用以下代码时:

feeds = Feed.includes(:user)

我想跳过用户的 default_scope.所以我试过了:

I want to skip over the default_scope for users. so I tried:

feeds = Feed.unscoped.includes(:user)

但这并没有从用户中删除范围.关于如何使其工作的任何建议?谢谢

But this is not removing the scope from users. Any suggestions on how I can get this to work? Thank you

推荐答案

您可以通过在块形式中使用 .unscoped 来完成此操作,如 此处:

You can accomplish this by using .unscoped in block form, as documented here:

User.unscoped do
  @feeds = Feed.includes(:user).all
end

请注意,默认范围是否适用取决于查询实际执行时您是否在块内.这就是为什么上面使用.all,强制执行查询.

Note that whether or not the default scope applies depends on whether or not you're inside the block when the query is actually executed. That's why the above uses .all, forcing the query to execute.

因此,虽然上述有效,但这不会 - 查询在 .unscoped 块之外执行并且将应用默认范围:

Thus, while the above works, this won't - the query is executed outside the .unscoped block and the default scope will apply:

User.unscoped do
  @feeds = Feed.includes(:user)
end
@feeds #included Users will have default scope

这篇关于如何在 Rails 3 中取消关联记录的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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