1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-05 08:08:02 +00:00

Add ActiveRecord Query For This Or That as a rails til

This commit is contained in:
jbranchaud
2019-05-28 18:17:05 -05:00
parent 52eb7123cb
commit f4b750f2e2
2 changed files with 28 additions and 1 deletions

View File

@@ -0,0 +1,26 @@
# ActiveRecord Query For This Or That
When including multiple `where` clauses on a query, we are adding more
specificity to the resulting `ActiveRecord` relation -- it's like saying we
want records that match this _and_ that. But what about when we want to find
records that match this _or_ that?
This is supported by `ActiveRecord` through the `or` query method.
Let's say we want all books that are either unpublished _or_ are published in
2019.
```ruby
> Book.where(status: 'unpublished').or(Book.where(publication_year: 2019))
=> #<ActiveRecord::Relation [...]>
```
This will generate SQL that includes a `where` clause like the following:
```sql
where (books.status = 'unpublished' or books.publication_year = 2019)
```
See the
[docs](https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-or)
for more details.