【问题标题】:Rails 3.1.3 unscoped scopeRails 3.1.3 无作用域
【发布时间】: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,则没有真正的解决方案)
  • 我想说也看看exceptonly,但他们似乎并没有从另一个范围内否定default_scope,类似于unscopedwith_exclusive_scope的问题.
  • 也许我遗漏了一些东西,但 scope :inactive, unscoped.where(:is_active => false) 在 Rails 3.1.3 应用程序上对我来说工作得很好。我在User 类上尝试过,调用User.inactive 只给我那些is_activefalse 的记录。
  • @DylanMarkow - 您是否将default_scope 设置为where(:is_active => true)

标签: ruby-on-rails activerecord ruby-on-rails-3.1 default-scope


【解决方案1】:

似乎没有办法做到这一点。我在 github 上的 rails repo 上打开了一个 issue...

【讨论】:

  • 作为一种变通方法,您可以创建一个使用非作用域且工作正常的类方法。
【解决方案2】:

试试这个

scope :inactive, lambda { unscoped.where(:is_active => false) }

【讨论】:

  • ftr,也没有 unscoped { lambda {...} }
猜你喜欢
  • 2012-02-14
  • 2012-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-16
  • 2012-02-03
  • 2012-02-12
  • 1970-01-01
相关资源
最近更新 更多