문제 설명
ROR + 모든 게시물에 대한 최신 또는 마지막 두 개의 댓글 가져오기 (ROR + Fetch latest or last two comments for every Post)
In my application, I have to fetch last/latest two comments from Comment model for Post model just like Facebook.
For every Post may be there is comment or not. For example :‑
Post 1 having 10 comments.
Post 2 having 5 comments.
Post 3 have no comments.
Post 5 have 20 comments.
Now I am not getting the way to find the last two comments for each Post and total number of comments with respect to that post. Can anyone suggest how to resolve this. Because I have an approach in my mind which is very worst, that by firing each loop for Post and find last/latest 2 comments.
Thanks in advance. Hoping for the best approach / method.
참조 솔루션
방법 1:
A naive approach: Assuming each post has a has_many :comments relationship, you could try:
comments = post.comments
total_comments = comments.count
last_two_comments = comments.last(2)
which would give you the last two comments for a post object. This will load all comments for each post, so may not be ideal performance wise. Alternatively you could do a query for comments where the post_id equals the post_id in question.
Something like:
Comment.where(post_id: post.id).limit(2).order("id DESC")