default_scope和关联 [英] default_scope and associations

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

问题描述

假设我有一个Post模型和一个Comment模型.使用通用模式,发布has_many条评论.

Suppose I have a Post model, and a Comment model. Using a common pattern, Post has_many Comments.

如果Comment设置了default_scope:

If Comment has a default_scope set:

default_scope where("deleted_at IS NULL")

无论范围如何,如何轻松检索帖子中的所有评论? 这将产生无效的结果:

How do I easily retrieve ALL comments on a post, regardless of scope? This produces invalid results:

Post.first.comments.unscoped

哪个会生成以下查询:

SELECT * FROM posts LIMIT 1;
SELECT * FROM comments;

代替:

SELECT * FROM posts LIMIT 1;
SELECT * FROM comments WHERE post_id = 1;

运行:

Post.first.comments

产生:

SELECT * FROM posts LIMIT 1;
SELECT * FROM comments WHERE deleted_at IS NULL AND post_id = 1;

我了解无范围删除所有现有范围的基本原理,但是它不应该意识到并保持关联范围吗?

I understand the basic principle of unscoped removing all existing scopes, but shouldn't it be aware and to keep the association scope?

提取所有评论的最佳方法是什么?

What is the best way to pull ALL comments?

推荐答案

出于某些奇怪的原因,

Comment.unscoped { Post.last.comments }

包括Commentdefault_scope

但是,

Comment.unscoped { Post.last.comments.to_a }
Comment.unscoped { Post.last.comments.order }

包含Commentdefault_scope.

我在Rails 3.2.3rails console会话中经历了这一点.

I experienced this in a rails console session with Rails 3.2.3.

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

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