Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Demonstrate how to use Relation#merge in Join Table conditions [ci skip] #40096

Merged
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 21 additions & 2 deletions guides/source/active_record_querying.md
Expand Up @@ -1243,7 +1243,7 @@ You can specify conditions on the joined tables using the regular [Array](#array

```ruby
time_range = (Time.now.midnight - 1.day)..Time.now.midnight
Customer.joins(:orders).where('orders.created_at' => time_range)
Customer.joins(:orders).where('orders.created_at' => time_range).distinct
```

This will find all customers who have orders that were created yesterday, using a `BETWEEN` SQL expression to compare `created_at`.
Expand All @@ -1252,7 +1252,26 @@ An alternative and cleaner syntax is to nest the hash conditions:

```ruby
time_range = (Time.now.midnight - 1.day)..Time.now.midnight
Customer.joins(:orders).where(orders: { created_at: time_range })
Customer.joins(:orders).where(orders: { created_at: time_range }).distinct
```

For more advanced conditions or to reuse an existing named scope, `Relation#merge` may be used. First, let's add a new named scope to the Order model:
danielricecodes marked this conversation as resolved.
Show resolved Hide resolved

```ruby
class Order < ApplicationRecord
belongs_to :customer

scope :created_in_time_range, ->(time_range) {
where(created_at: time_range)
}
end
```

Now we can use `Relation#merge`:
danielricecodes marked this conversation as resolved.
Show resolved Hide resolved

```ruby
time_range = (Time.now.midnight - 1.day)..Time.now.midnight
Customer.joins(:orders).merge(Order.created_in_time_range(time_range)).distinct
```

This will find all customers who have orders that were created yesterday, again using a `BETWEEN` SQL expression.
Expand Down