Skip to content

Instantly share code, notes, and snippets.

@niconegoto
Created August 25, 2018 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niconegoto/a9e6e80ac951cebc7797f99afba72528 to your computer and use it in GitHub Desktop.
Save niconegoto/a9e6e80ac951cebc7797f99afba72528 to your computer and use it in GitHub Desktop.
```
# コメントは2階層で、親→子はreplies、子→親はparentとして参照する
class Comment < ApplicationRecord
belongs_to :article
belongs_to :parent, class_name: :Comment, optional: true
has_many :replies, class_name: :Comment, foreign_key: :parent_id
end
```
```scope :with_all_comments, -> {
eager_load(comments: :replies).where(comments: {parent_id: nil})
}
```
```
# articles.comments はwith_all_commentsによって得られた、parent_idが空の(親階層の)comments
replies = Comment.find_by_sql [
# 各コメントに対して最新の返信1件のみを取得したい
"
select * from comments where id in (
select max(id) from comments where parent_id in (?) group by parent_id
)
",
articles.flat_map(&:comment_ids)
]
articles.each do |a|
a.comments.each do |c|
# TODO: use group_by
c.replies = replies.select do |r|
r.parent_id == c.id
end
end
end
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment