LoginSignup
0
0

More than 3 years have passed since last update.

ActiveRecord の関連をどんどんたどっていく

Posted at

こんな感じの Model があるとする。

class Company < ApplicationRecord
  has_many :users
end

class User < ApplicationRecord
  has_many :posts
end

class Post < ApplicationRecord
  has_many :comments
end

class Comment < ApplicationRecord
end

Company が持っている Post をすべて取得

class Company < ApplicationRecord
  has_many :users
  has_many :posts, through: :users
end

ってしてやると、以下でまとめて取得できる。

# Company が持っている Post をすべて取得
Company.first.posts

Company が持っている Comment をすべて取得

class Company < ApplicationRecord
  has_many :users
  has_many :posts, through: :users
  has_many :comments, through: :posts
end

ってしてやると、以下でまとめて取得できる。

# Company が持っている Comment をすべて取得
Company.first.comments

ApplicationRecord って本当になんでもいい感じでやってくれる!

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