How to show 3 records the first time then 8 records the next request using will_paginate

StackOverflow https://stackoverflow.com/questions/20257053

  •  05-08-2022
  •  | 
  •  

質問

I use will_paginate gem in my rails app, in my articles i have comments so the first time when user show an article, he can see this article with just 3 first comments, then if he clicks a show more link (which is a remote link/"ajax"), he will see the next 8 comments, i try to use

in my article view i render a partial that show comments like this :

= 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

if the user clicks the show more link, an ajax request will trigger my index action which is in comment controller (i want here to show the 8 next elements) :

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

but its not working correctly, when i click show more the first time it skip 5 elements (8 - 3) then it show me the 8 next elements

there is a way to solve this ?

役に立ちましたか?

解決 2

i solved my problem by retrieve the 5 records that will_paginate skip before rendering records in page 2

in my index.js.erb i do :

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

if you have any other suggestion, i will be thankful :)

他のヒント

I am not sure if your index action is used some other place as well but you can try:

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

and your link should render page 1:

= link_to 'Show more', article_comments_path(article.id, :page => 1), :remote => true
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top