複数のテーブルを結合して取得
適応バージョン
- 3.0.0
- 3.0.5
- 3.0.7
- 3.0.9
- 3.1.0
- 3.2.3
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.2.1
- 7.0.0
説明
複数のテーブルを結合して取得
使い方
モデル.joins(条件)
例
categoryテーブルにpostテーブルを結合して取得
Category.joins(:posts)
# SELECT categories.* FROM categories INNER JOIN posts ON posts.category_id = categories.id
2個のテーブルをjoin
Post.joins(:category, :comments)
# SELECT posts.* FROM posts
# INNER JOIN categories ON posts.category_id = categories.id
# INNER JOIN comments ON comments.post_id = posts.id
ネストして結合
Page.joins(categories: :element)
# SELECT "pages".* FROM "pages" INNER JOIN "pages_categories" ON "pages_categories"."page_id" = "pages"."id" INNER JOIN "categories" ON "categories"."id" = "pages_categories"."category_id" INNER JOIN "elements" ON "elements"."id" = "categories"."element_id"
SQLで記述
User.joins("LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id")
# SELECT "users".* FROM "users" LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id