Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 - Do not scope if conditions

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

like image 542
pierallard Avatar asked Mar 18 '23 18:03

pierallard


1 Answers

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
}

؜ᅟᅠ             ⁠ㅤ

like image 57
Marek Lipka Avatar answered Mar 24 '23 12:03

Marek Lipka