LoginSignup
1
0

More than 3 years have passed since last update.

Rails 親id1番の孫データを全件取得する方法

Posted at

はじめに

以下のように企業⇒従業員⇒予定の親子孫関係がある際に、
企業IDが1番の従業員が作成した予定を、全件取得する方法について記載します。
image.png

条件

モデルの関連付けは以下のようになっています。

class Company < ApplicationRecord
  has_many :employees

class Employee < ApplicationRecord
  belongs_to :company
  has_many :schedules

class Schedule < ApplicationRecord
  belongs_to :employee

結論

以下記述で取得可能となります。

SchedulesController
@schedules = Schedule.where(employee_id: Company.find(1).employees.ids)

内容

まず、companyのid1番のデータをfindメソッドを使用し取得します

Company.find(1)

取得したものに対し、.employees.idsを行うことで、
企業IDが1番の従業員IDの番号を、配列の形式で得ることが可能になります。

Company.find(1).employees.ids 
# 例)[2, 3, 4, 5, 6, 7]

その配列を用いてScheduleモデルにwhereメソッドを使用すると、
企業IDが1番の従業員が作成した予定を、全件取得する事ができます。

Schedule.where(employee_id: Company.find(1).employees.ids)
1
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
1
0