Last active
July 11, 2020 10:18
-
-
Save Arakaki-Yuji/766cc54ed18ba859881a to your computer and use it in GitHub Desktop.
RailsのActiveRecordで親要素から孫要素を参照する場合
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# includesでentriesとそれに紐づくcommentsをロードしておく。 | |
# そうすることで以後の処理でentriesとそれに紐づくcommentsを取得するさいに | |
# 毎回SQLを発行することを防ぐ。 | |
# | |
# includesのかわりにjoinsを使うと事前ロードはされないため、 | |
# 以後の処理でSQLが吐かれてしまうので注意する。 | |
# | |
blog = Blog.includes(:entries => :comments).find_by_id(1) | |
# | |
# blogに紐づく各entryのcommetsを取得する | |
# ただしこのままだと | |
# [[Comment, Comment, Comment], [Comment, Comment, Comment]] | |
# のように各エントリのコメントが別々のcollectionに入って取得されるので | |
# flattenで配列を平坦化して | |
# [Comment Comment, Comment, Comment, Comment, Comment] | |
# のようにする。 | |
# | |
# | |
blog.entries.map{ |entry| entry.comments }.flatten |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment