Rails 4 - Do not scope if conditions

独自空忆成欢 提交于 2019-12-22 09:38:54

问题


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 ?

Regards


回答1:


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


来源:https://stackoverflow.com/questions/25241116/rails-4-do-not-scope-if-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!