我想创建一个具有某些条件的范围,其中一个不返回特定范围。目前,此解决方案有效:
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
}
有没有其他更好的解决方案来做到这一点?
问候
最佳答案
在 Rails 4 中,你可以简单地使用 all
:
scope :my_scope, ->(my_var) {
if my_var.condition?
where(some_condition: :some_value)
else
all
end
end
关于ruby-on-rails - Rails 4 - 如果条件不适用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25241116/