Skip to content

Commit f4b750f

Browse files
committed
Add ActiveRecord Query For This Or That as a rails til
1 parent 52eb712 commit f4b750f

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010
For a steady stream of TILs from a variety of rocketeers, checkout
1111
[til.hashrocket.com](https://til.hashrocket.com/).
1212

13-
_815 TILs and counting..._
13+
_816 TILs and counting..._
1414

1515
---
1616

@@ -476,6 +476,7 @@ _815 TILs and counting..._
476476

477477
- [Add React With Webpacker To A New Rails App](rails/add-react-with-webpacker-to-a-new-rails-app.md)
478478
- [Access Secrets In A Rails 5.2 App](rails/access-secrets-in-a-rails-5-2-app.md)
479+
- [ActiveRecord Query For This Or That](rails/active-record-query-for-this-or-that.md)
479480
- [Advance The Date](rails/advance-the-date.md)
480481
- [All or Nothing Database Transactions](rails/all-or-nothing-database-transactions.md)
481482
- [Attach A File With Capybara](rails/attach-a-file-with-capybara.md)
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# ActiveRecord Query For This Or That
2+
3+
When including multiple `where` clauses on a query, we are adding more
4+
specificity to the resulting `ActiveRecord` relation -- it's like saying we
5+
want records that match this _and_ that. But what about when we want to find
6+
records that match this _or_ that?
7+
8+
This is supported by `ActiveRecord` through the `or` query method.
9+
10+
Let's say we want all books that are either unpublished _or_ are published in
11+
2019.
12+
13+
```ruby
14+
> Book.where(status: 'unpublished').or(Book.where(publication_year: 2019))
15+
=> #<ActiveRecord::Relation [...]>
16+
```
17+
18+
This will generate SQL that includes a `where` clause like the following:
19+
20+
```sql
21+
where (books.status = 'unpublished' or books.publication_year = 2019)
22+
```
23+
24+
See the
25+
[docs](https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-or)
26+
for more details.

0 commit comments

Comments
 (0)