0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Rails】category_id = 1 の sub_category を持つ items を取得したい。(サブクエリ)

0
Posted at

Diagram

category_id = 1 の sub_category を持つ items を取得したい。

:point_down: SQL

SQL
-- サブクエリ(副問合せ)を使います。
SELECT * FROM items WHERE sub_category_id IN
(SELECT * FROM sub_categories WHERE category_id = 1);

:point_down: Rails

Rails
sub_categories = SubCategory.where(category_id: 1)
@items = Item.where(sub_category: sub_categories)

# => #<ActiveRecord::Relation [#<Item id: 1, name: "apple juice", sub_category_id: 1>, #<Item id: 2, name: "orange juice", sub_category_id: 1>, #<Item id: 3, name: "coca cola", sub_category_id: 2>, ...]>

.where(category_id: 1) のところは、.where(category: @category) でもOK。

これでできました。:thumbsup:

まさか.where()でActiveRecordの問合せ結果を渡すことができるとは知らなかったですね...
かなり基礎的なことですが、Rails/SQL初心者の自分は、これを探し出すのに地味に苦労しました。
これが誰かのお役立てできれば幸いです。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?