From e63928445f828b0a89f89df0c6a058eddf69d69e Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 11 Apr 2019 10:13:34 -0500 Subject: [PATCH] Add Disambiguate Where In A Joined Relation as a rails til --- README.md | 3 +- ...disambiguate-where-in-a-joined-relation.md | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 rails/disambiguate-where-in-a-joined-relation.md diff --git a/README.md b/README.md index 9ff96cb..8af8113 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/). -_802 TILs and counting..._ +_803 TILs and counting..._ --- @@ -490,6 +490,7 @@ _802 TILs and counting..._ - [Custom Validation Message](rails/custom-validation-message.md) - [Delete Paranoid Records](rails/delete-paranoid-records.md) - [Demodulize A Class Name](rails/demodulize-a-class-name.md) +- [Disambiguate Where In A Joined Relation](rails/disambiguate-where-in-a-joined-relation.md) - [Generating And Executing SQL](rails/generating-and-executing-sql.md) - [Hash Slicing](rails/hash-slicing.md) - [Ignore Poltergeist JavaScript Errors](rails/ignore-poltergeist-javascript-errors.md) diff --git a/rails/disambiguate-where-in-a-joined-relation.md b/rails/disambiguate-where-in-a-joined-relation.md new file mode 100644 index 0000000..ac41bea --- /dev/null +++ b/rails/disambiguate-where-in-a-joined-relation.md @@ -0,0 +1,29 @@ +# Disambiguate Where In A Joined Relation + +When you join two tables using ActiveRecord + +```ruby +Post.joins(:author) +``` + +You get a relation that involves both of the tables. This allows you to +write queries that work off the data in that join. + +The primary table in the join is `posts`. Any column references in a +`#where` call will be assumed to be related to `posts`. If you want to +reference a column on the `authors` table, you'll need to provide that +specificity. + +The hash syntax for `#where` is a great way to do that: + +```ruby +Post.joins(:author).where({ authors: { name: "John Steinbeck" }}) +``` + +You can also use the string syntax: + +```ruby +Post.joins(:author).where("authors.name = ?", "John Steinbeck") +``` + +[source](https://apidock.com/rails/v4.2.7/ActiveRecord/QueryMethods/where)