What is good way to limit the amount of comments shown to a user until they choose to view all?

丶灬走出姿态 提交于 2019-12-04 17:53:33

You can do like Facebook:

  • Show only 2/3 comments. Load only 2/3 comments from the backend.
  • When the users clicks "Show more", it shows 50 more. It loads them through AJAX. So on the backend you only get a request like "GET 50 comments EXCEPT the three firsts".
  • Another "Show more" link is shown. It will load 50 other comments except the 53 firsts.

On Facebook, you can't load more than 50 comments at once. I think you should do the same.

The clean way is to implement pagination for comments.

I suppose there's a simple belongs_to and has_many relationship between Post and Comment. I normally will do:

routes:

resources :posts do
  resources :comments
end

model: set a default page size:

class Comments < ActiveRecord::Base
  belongs_to :post

  DEFAULT_PAGE_SIZE = 25
end

controller:

class CommentsController
  def index
    post = Post.find(params[:post_id])
    offset = params[:offset] || 0
    limit = params[:limit] || Comment::DEFAULT_PAGE_SIZE
    @comments = post.comments.offset(offset).limit(limit)

    respond_to do |format|
      #respond as you like
    end
  end

  # more actions...
end

view, a load more link something like, to load the comments via ajax:

<%= link_to "load more comments", post_comments_path(@post, :format => 'js'), :method => :get, :remote=>true id='load-more-comments' %>

and you also would like to bind the offset to the ajax post:

$ ->
  $('#load-more-comments').on 'ajax:before', (event) ->
    el = $(this)
    offset = #count your offset, I often do by counting the <li>s already in the <ul>
    el.data 'params', "offset=#{offset}"
    # you could also pass the limit: el.data 'params', "offset=#{offset}&limit=#{some limit}"
  .on 'ajax:complete', (event, xhr, status) ->
    el = $(this)
    el.removeData 'params' # remember to remove this.

I am also interested in what's the better way to do this. Looking forward to the answers and critics. :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!