Rails 4 - 如果条件不适用 [英] Rails 4 - Do not scope if conditions

查看:48
本文介绍了Rails 4 - 如果条件不适用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create a scope with some conditions, with one returning not a specific scope. For now, this solution works:

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 
}

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

Is there any other better solution to do this ?

问候

推荐答案

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

In Rails 4, you can simply use all:

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

这篇关于Rails 4 - 如果条件不适用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆