【问题标题】:Rails 4 - Do not scope if conditionsRails 4 - 如果条件不范围
【发布时间】:2014-10-04 03:41:39
【问题描述】:

我想创建一个具有某些条件的范围,其中一个返回的不是特定范围。目前,此解决方案有效:

scope :my_scope, ->(my_var) {
  scope = where('TRUE')
  if my_var.condition1?
     scope = scope.where({ :some_condition => :some_value })
  end
  if my_var.condition2?
     scope = scope.where({ :some_condition => :some_value })
  end
  scope 
}

还有其他更好的解决方案吗?

问候

【问题讨论】:

  • 我很确定您可以放心地在 where 之前省略 .。我在我的代码中使用了相同的解决方案并且效果很好。考虑给出一个不太通用的答案以获得深入的答案。
  • @MichalSzyndel 已修复。
  • 是的,但我的问题实际上是关于my_var 以及您检查它的什么样的条件?根据这一点,您可能会以不同的方式处理此问题。正如我所说,我自己在作用域中使用条件,但不会说我认为这是一个很好的做法。

标签: ruby-on-rails ruby-on-rails-4 scope


【解决方案1】:

在 Rails 4 中,您可以简单地使用 all

scope :my_scope, ->(my_var) {
  if my_var.condition?
    where(some_condition: :some_value)
  else
    all
  end
}

؜ᅟᅠ            ⁠ㅤ

【讨论】:

  • all 不加载我所有的 AR 对象吗?
  • 否 - 例如:Model.custom_scope.all 返回范围为 custom_scope 的结果。
  • 是的,但是Model.all.custom_scope ?我有几个像这样链接的范围。
  • Model.all.custom_scope == Model.custom_scope.all。由于 Rails 4 这不是问题(因为在 Rails 4 中 all 返回 ActiveRecord::Relation 而不是 Array)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 1970-01-01
  • 2017-06-25
  • 2016-07-11
  • 2016-08-23
  • 1970-01-01
相关资源
最近更新 更多