Skip to content

Commit d4f48a4

Browse files
committed
Add Merge A Scope Into An ActiveRecord Query as a rails til
1 parent 957d145 commit d4f48a4

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-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-
_818 TILs and counting..._
13+
_819 TILs and counting..._
1414

1515
---
1616

@@ -504,6 +504,7 @@ _818 TILs and counting..._
504504
- [Mark A Migration As Irreversible](rails/mark-a-migration-as-irreversible.md)
505505
- [Make ActionMailer Synchronous In Test](rails/make-action-mailer-synchronous-in-test.md)
506506
- [Mark For Destruction](rails/mark-for-destruction.md)
507+
- [Merge A Scope Into An ActiveRecord Query](rails/merge-a-scope-into-an-activerecord-query.md)
507508
- [Migrating Up Down Up](rails/migrating-up-down-up.md)
508509
- [Params Includes Submission Button Info](rails/params-includes-submission-button-info.md)
509510
- [Perform SQL Explain With ActiveRecord](rails/perform-sql-explain-with-activerecord.md)
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Merge A Scope Into An ActiveRecord Query
2+
3+
Consider an ActiveRecord model with a scope:
4+
5+
```ruby
6+
class Book < ApplicationRecord
7+
scope :published, -> { where("books.published_at is not null") }
8+
end
9+
```
10+
11+
Now let's say we are working in another part of the codebase composing a query
12+
that gathers all authors with published books. That might look something like
13+
this:
14+
15+
```ruby
16+
published_authors =
17+
Authors.joins(:book).where("books.published_at is not null")
18+
```
19+
20+
This will get the job done, but we've now duplicated the same logic in
21+
different parts of the app. We can utilize the existing scope on `Book` using
22+
ActiveRecord's
23+
[`merge`](https://devdocs.io/rails~5.2/activerecord/spawnmethods#method-i-merge)
24+
method.
25+
26+
```ruby
27+
published_authors =
28+
Authors.joins(:book).merge( Book.published )
29+
```
30+
31+
The `merge` method can be used to incorporate any conditions from other partial
32+
queries -- this means both `where` clauses and `joins` clauses.
33+
34+
[source](http://aokolish.me/blog/2015/05/26/how-to-simplify-active-record-scopes-that-reference-other-tables/)

0 commit comments

Comments
 (0)