【问题标题】:How to show 3 records the first time then 8 records the next request using will_paginate如何第一次显示 3 条记录,然后使用 will_paginate 显示 8 条记录下一个请求
【发布时间】:2013-11-28 03:11:50
【问题描述】:

我在我的 rails 应用程序中使用 will_paginate gem,在我的文章中我有 cmets,所以当用户第一次展示一篇文章时,他可以看到这篇文章只有 3 个第一个 cmets,然后如果他点击一个显示更多链接(即一个远程链接/“ajax”),他将看到接下来的 8 个 cmets,我尝试使用

在我的文章视图中,我渲染了一个显示 cmets 的部分:

= render partial: "shared/comments", collection: article.comments.paginate(page: params[:page], per_page: 3)  # i use paginate to show just 3 comments
= link_to 'Show more', article_comments_path(article.id, :page => 2), :remote => true

如果用户单击显示更多链接,ajax 请求将触发我在评论控制器中的索引操作(我想在这里显示 8 个下一个元素):

def index
  @comments = @commentable.comments.paginate(page: params[:page], per_page: 8)
end

但它不能正常工作,当我第一次点击显示更多时它会跳过 5 个元素(8 - 3)然后它会显示 8 个下一个元素

有办法解决这个问题吗?

【问题讨论】:

    标签: ruby-on-rails will-paginate


    【解决方案1】:

    我不确定您的 index 操作是否也用于其他地方,但您可以尝试:

    def index
      @comments = @commentable.comments.offset(3).paginate(page: params[:page], per_page: 8)
    end
    

    并且您的链接应该呈现第 1 页:

    = link_to 'Show more', article_comments_path(article.id, :page => 1), :remote => true
    

    【讨论】:

    • 这个不行,因为第二次page >= 2时,总是使用offset(3) ...
    【解决方案2】:

    我通过在第 2 页中呈现记录之前检索 will_paginate 跳过的 5 条记录解决了我的问题

    在我的 index.js.erb 我做:

    <% if @comments.current_page == 2  %>
        <% @x = @commentable.comments.offset(3).limit(2) # get the 5 skipped records %> 
    <% else %>
        <% @x = "" %>
    <% end %>
    
    $("div#comments").append("<%= escape_javascript(render partial: 'shared/comments', collection: @x) %>")
    $("div#comments").append("<%= escape_javascript(render partial: 'shared/comments', collection: @comments) %>")
    

    如果您有任何其他建议,我将不胜感激:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多