Skip to content

Commit e639284

Browse files
committed
Add Disambiguate Where In A Joined Relation as a rails til
1 parent 1cade78 commit e639284

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-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-
_802 TILs and counting..._
13+
_803 TILs and counting..._
1414

1515
---
1616

@@ -490,6 +490,7 @@ _802 TILs and counting..._
490490
- [Custom Validation Message](rails/custom-validation-message.md)
491491
- [Delete Paranoid Records](rails/delete-paranoid-records.md)
492492
- [Demodulize A Class Name](rails/demodulize-a-class-name.md)
493+
- [Disambiguate Where In A Joined Relation](rails/disambiguate-where-in-a-joined-relation.md)
493494
- [Generating And Executing SQL](rails/generating-and-executing-sql.md)
494495
- [Hash Slicing](rails/hash-slicing.md)
495496
- [Ignore Poltergeist JavaScript Errors](rails/ignore-poltergeist-javascript-errors.md)
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Disambiguate Where In A Joined Relation
2+
3+
When you join two tables using ActiveRecord
4+
5+
```ruby
6+
Post.joins(:author)
7+
```
8+
9+
You get a relation that involves both of the tables. This allows you to
10+
write queries that work off the data in that join.
11+
12+
The primary table in the join is `posts`. Any column references in a
13+
`#where` call will be assumed to be related to `posts`. If you want to
14+
reference a column on the `authors` table, you'll need to provide that
15+
specificity.
16+
17+
The hash syntax for `#where` is a great way to do that:
18+
19+
```ruby
20+
Post.joins(:author).where({ authors: { name: "John Steinbeck" }})
21+
```
22+
23+
You can also use the string syntax:
24+
25+
```ruby
26+
Post.joins(:author).where("authors.name = ?", "John Steinbeck")
27+
```
28+
29+
[source](https://apidock.com/rails/v4.2.7/ActiveRecord/QueryMethods/where)

0 commit comments

Comments
 (0)