0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

railsでテーブルを関連付けした際のwhereでのカラムの指定の仕方について

Last updated at Posted at 2024-07-22
  • includes
  • preload
  • eager_load

などで関連テーブルを読み込んだ際に、whereメソッドから関連テーブルのカラムを参照したい場合はreferencesキーワードを使って関連テーブル名を宣言する必要がある

 User.includes(:posts).where("posts.name = 'foo'")
  # Doesn't JOIN the posts table, resulting in an error.  
 User.includes(:posts).where("posts.name = 'foo'").references(:posts)  
 # Query now knows the string references posts, so adds a JOIN

joinsメソッドを使う際は不要だと思うが、incluedesなどの関連付けをeager loadingするメソッドを採用した際にはreferencesメソッドの出番になる感じだと思う
https://api.rubyonrails.org/v7.1/classes/ActiveRecord/QueryMethods.html#method-i-references

joinsメソッドを使った際はこんな感じでwhereを指定できる

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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?