From f4b750f2e2dd64fa5f040f588e32bf5be706770c Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 28 May 2019 18:17:05 -0500 Subject: [PATCH] Add ActiveRecord Query For This Or That as a rails til --- README.md | 3 ++- rails/active-record-query-for-this-or-that.md | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 rails/active-record-query-for-this-or-that.md diff --git a/README.md b/README.md index 8e3ab7f..ada02b8 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_815 TILs and counting..._ +_816 TILs and counting..._ --- @@ -476,6 +476,7 @@ _815 TILs and counting..._ - [Add React With Webpacker To A New Rails App](rails/add-react-with-webpacker-to-a-new-rails-app.md) - [Access Secrets In A Rails 5.2 App](rails/access-secrets-in-a-rails-5-2-app.md) +- [ActiveRecord Query For This Or That](rails/active-record-query-for-this-or-that.md) - [Advance The Date](rails/advance-the-date.md) - [All or Nothing Database Transactions](rails/all-or-nothing-database-transactions.md) - [Attach A File With Capybara](rails/attach-a-file-with-capybara.md) diff --git a/rails/active-record-query-for-this-or-that.md b/rails/active-record-query-for-this-or-that.md new file mode 100644 index 0000000..5668f81 --- /dev/null +++ b/rails/active-record-query-for-this-or-that.md @@ -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)) +=> # +``` + +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.