覆盖 Rails default_scope [英] Overriding a Rails default_scope
问题描述
如果我有一个默认范围的 ActiveRecord::Base 模型:
If I have an ActiveRecord::Base model with a default-scope:
class Foo < ActiveRecord::Base
default_scope :conditions => ["bar = ?",bar]
end
有没有办法使用 default_scope
条件来做一个 Foo.find
没有?换句话说,您可以覆盖默认范围吗?
Is there any way to do a Foo.find
without using the default_scope
conditions? In other words, can you override a default scope?
我原以为在名称中使用default"表示它是可覆盖的,否则它会被称为global_scope
之类的东西,对吗?
I would have thought that using 'default' in the name would suggest that it was overridable, otherwise it would be called something like global_scope
, right?
推荐答案
简短回答:除非确实必须,否则不要使用 default_scope
.使用命名范围可能会更好.话虽如此,如果需要,您可以使用 with_exclusive_scope
来覆盖默认范围.
Short answer: Do not use default_scope
unless you really have to. You'll probably be better off with named scopes. With that said, you can use with_exclusive_scope
to override the default scope if you need to.
看看 这个问题了解更多详情.
这篇关于覆盖 Rails default_scope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!