Rails will_paginate 链接不正确

Rails will_paginate links incorrect

我有一个显示文章、相关评论和用于添加新评论的表单的视图。评论列表使用 will_paginate 分页,新评论使用 ajax.

添加

页面加载后link如下:

http://localhost:3000/articles/25?page=1

添加新评论时,comments#create 操作会初始化 @comments 变量并使用 ajax 更新分页,但创建的 link 不正确:

http://localhost:3000/articles/25/comments?page=1

文章控制器

def show
  @article  = Article.find(params[:id])
  @comments = @article.comments.order(created_at: :asc).page(params[:page]).per_page(5)
  @comment  = @article.comments.new
end

评论控制器

def create
  @article = Article.find(params[:article_id])
  @comment = @article.comments.new(comment_params)
  @comment.user_id = current_user.id

  if @comment.save
    @comments = @article.comments.order(created_at: :asc).page(params[:page]).per_page(5)
  end
  render :action => 'create.js.erb'
end

create.js.erb

<% if @comment.errors.any? %>
  $('#error_explanation').remove();
  $('#comment-form').prepend('<%= j render 'shared/error_messages', object: @comment %>');
<% else %>
  $("#comment-form")[0].reset();
  $('#comments').html('<%= j render partial: @comments %>');
  $('.digg_pagination').remove();
  $('#comments').append('<%= will_paginate @comments, class: "digg_pagination" %>');
<% end %>

will_paginate 使用当前 URL 创建一个 URL 并在其末尾附加 "page"。

由于它来自用于评论的创建操作,因此将其作为起点 URL:

http://localhost:3000/articles/25/comments

您可以通过使用特定参数来更改此设置,详情如下:https://github.com/mislav/will_paginate/wiki/API-documentation

这应该可以解决问题:

 $('#comments').append('<%= will_paginate @comments, class: "digg_pagination" %>')

 $('#comments').append('<%= will_paginate @comments, class: "digg_pagination", :params => { :controller => "articles", :action => "show" } %>')

:params 允许您更改 url_for 方法使用的参数。您可以在此处查看有关 url_for 的信息:http://apidock.com/rails/ActionController/Base/url_for