> For the complete documentation index, see [llms.txt](https://ploegert.gitbook.io/til/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ploegert.gitbook.io/til/programmy/rails/merge-a-scope-into-an-activerecord-query.md).

# Merge A Scope Into An ActiveRecord Query

Consider an ActiveRecord model with a scope:

```ruby
class Book < ApplicationRecord
  scope :published, -> { where("books.published_at is not null") }
end
```

Now let's say we are working in another part of the codebase composing a query that gathers all authors with published books. That might look something like this:

```ruby
published_authors =
  Authors.joins(:book).where("books.published_at is not null")
```

This will get the job done, but we've now duplicated the same logic in different parts of the app. We can utilize the existing scope on `Book` using ActiveRecord's [`merge`](https://devdocs.io/rails~5.2/activerecord/spawnmethods#method-i-merge) method.

```ruby
published_authors =
  Authors.joins(:book).merge( Book.published )
```

The `merge` method can be used to incorporate any conditions from other partial queries -- this means both `where` clauses and `joins` clauses.

[source](http://aokolish.me/blog/2015/05/26/how-to-simplify-active-record-scopes-that-reference-other-tables/)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ploegert.gitbook.io/til/programmy/rails/merge-a-scope-into-an-activerecord-query.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
