Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Compare: Tips and tricks

Showing with 26 additions and 1 deletion.
  1. +26 −1 Tips-and-tricks.md
27 Tips-and-tricks.md
View
@@ -38,4 +38,29 @@ To invert the set that this query will return, use the unary operator <code>-</c
```ruby
Person.where{-((name =~ 'Ernie%') & (salary < 50000) | (name =~ 'Joe%') & (salary > 100000))}
-```
+```
+
+## Dynamic Queries
+
+For simple `AND` queries use multiple calls to `where`:
+
+```ruby
+q = Person.where{name =~ 'Ernie%'}
+q = q.where{salary < my{max_salary}} if max_salary
+```
+
+For `OR` or nested queries:
+
+```ruby
+where{
+ q = (name =~ "Ernie%")
+ q |= (salary < my{max_salary}) if my{max_salary}
+ q
+}
+```
+
+Alternatively:
+
+```ruby
+where{[(name =~ "Ernie%"), (salary < my{max_salary} if my{max_salary})].compact.inject(&:|)}
+```
Something went wrong with that request. Please try again.