pie*_*ard 3 scope ruby-on-rails ruby-on-rails-4
我想创建一个具有某些条件的范围,其中一个返回不是特定范围.目前,此解决方案有效:
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
}
Run Code Online (Sandbox Code Playgroud)
还有其他更好的解决方案吗?
问候
在Rails 4中,您可以简单地使用all:
scope :my_scope, ->(my_var) {
if my_var.condition?
where(some_condition: :some_value)
else
all
end
end
Run Code Online (Sandbox Code Playgroud)