こんな感じの 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 って本当になんでもいい感じでやってくれる!