ROR + 모든 게시물에 대한 최신 또는 마지막 두 개의 댓글 가져오기 (ROR + Fetch latest or last two comments for every Post)


문제 설명

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")

(by RubyistPuhlze)

참조 문서

  1. ROR + Fetch latest or last two comments for every Post (CC BY‑SA 3.0/4.0)

#facebook-comments #ruby-on-rails-3.2






관련 질문

ROR + 모든 게시물에 대한 최신 또는 마지막 두 개의 댓글 가져오기 (ROR + Fetch latest or last two comments for every Post)

Facebook에 다시 게시하지 않고 Facebook 댓글을 사용하시겠습니까? (Use Facebook Comments without posting back to Facebook?)

뉴스피드에 댓글 올리기 (Posting a comment on the news feed)

Facebook 댓글이 extjs 컨테이너에 표시되지 않습니다. (Facebook comments don't appear in extjs container)

Facebook 댓글 소셜 플러그인에 댓글을 추가할 수 있는 API가 있습니까? (Does the Facebook Comments Social Plugin have an API where comments can be added?)

자동 생성된 페이스북 댓글 상자 (Auto-generated facebook comments boxes)

Facebook 댓글 상자가 설치되었지만 중재자 보기 탭이 표시되지 않음 (Facebook Comment box Installed OK but moderator view tab not showing)

포스트백을 시도할 때 Oauth 예외 발생 (Getting Oauth Exceptions When trying to postback)

페이스북 댓글 - 중재를 허용하지 않습니다. (facebook comments - doesn't let me moderate)

같은 페이지에서 Facebook 좋아요 및 Facebook 댓글 활성화 (Activate Facebook like and facebook comment on same page)

웹사이트의 Facebook 댓글(사이트의 다른 페이지에서 작동하도록 만들기) (Facebook Comments on a Website (Making it work with diffrent pages on the site))

Facebook 댓글이 때때로 로드되지 않음 (Facebook Comments sometimes not loading)







코멘트