如何禁用belongs_to的default_scope? [英] How to disable default_scope for a belongs_to?
问题描述
有没有办法为单个 belongs_to
关联禁用 default_scope
?default_scope
适用于所有但我想绕过范围的单个 belongs_to
.我对 with_exclusive_scope
很熟悉,但我认为它不能与belongs_to 一起使用.
Is there a way to disable the default_scope
for a single belongs_to
association? The default_scope
is fine for all but a single belongs_to
that I would like to bypass the scope. I'm familiar with with_exclusive_scope
however I don't think that can be used with belongs_to.
有什么建议吗?
上下文:我试图在 acts_as_revisable 中允许 branch_source
关联指向不是最新的修订版(revisable_is_current
为假).
Context: I'm trying to allow the branch_source
association in acts_as_revisable to point to a revision that is not the latest (revisable_is_current
is false).
推荐答案
参加聚会可能有点晚(仅差 3 年),但遇到了同样的问题,Tobias 的解决方案肯定是正确的方向,但它可以简化为 Rails 3.2+.我唯一仍然不喜欢的是 Document 的硬编码"类名,也许可以使用反射来变形...
Probably a bit late to the party (just short of 3 years), but just run into the same problem and the solution from Tobias is certainly the right direction, but it can be simplified for Rails 3.2+. The only thing I still don't like is the "hard coded" class name for Document, maybe it's possible to inflect using reflection...
无论如何这是我想出的:
Anyhow this is what I've come up with:
class Comment < ActiveRecord::Base
# Document has some kind of default_scope
belongs_to :document
# Ensure document is not scoped, because Rails 3.2 uses modules it's
# possible to use simple inheritance.
def document
Document.unscoped { super }
end
end
更新:基于reflect_on_associationhttps://gist.github.com/2923336<获得了通用解决方案/a>
Update: got a generic solution, based on reflect_on_association https://gist.github.com/2923336
这篇关于如何禁用belongs_to的default_scope?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!