【发布时间】:2012-01-04 21:59:52
【问题描述】:
我看过很多关于这个的帖子,但似乎没有一个能解决我的问题。我在这样的模型上有一个default_scope:
default_scope where(:is_active => true).order('LOWER(table.name)');
我有其他(普通)作用域,我想使用unscoped 创建一个inactive 作用域。我想将它定义为一个范围,但它只在定义为类方法时才有效:
# works
def self.inactive
unscoped { where(:is_active => false) }
end
# none of these work
scope :inactive, unscoped { where(:is_active => false) }
scope :inactive, with_exclusive_scope { where(:is_active => true) }
scope :inactive, unscoped.where(:is_active => false)
scope :inactive, lambda { unscoped { where(:is_active => false) } }
scope :inactive, unscoped { lambda { where(:is_active => false) } }
unscoped do
scope :inactive, where(:is_active => false)
end
有没有我错过的方法,或者我必须使用类方法来定义这个范围?
【问题讨论】:
-
(如果您阅读那里的 cmets,则没有真正的解决方案)
-
我想说也看看
except和only,但他们似乎并没有从另一个范围内否定default_scope,类似于unscoped和with_exclusive_scope的问题. -
也许我遗漏了一些东西,但
scope :inactive, unscoped.where(:is_active => false)在 Rails 3.1.3 应用程序上对我来说工作得很好。我在User类上尝试过,调用User.inactive只给我那些is_active是false的记录。 -
@DylanMarkow - 您是否将
default_scope设置为where(:is_active => true)?
标签: ruby-on-rails activerecord ruby-on-rails-3.1 default-scope