Rails will_paginate链接不正确

时间:2015-10-02 19:48:02

标签: jquery ruby-on-rails ajax will-paginate

我有一个视图,显示文章,相关评论和添加新评论的表单。使用will_paginate对注释列表进行分页,并使用ajax添加新注释。

加载页面时,链接如下:

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

当添加新注释时,注释#create action会初始化@comments变量并使用ajax更新分页但是创建的链接不正确:

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

1 个答案:

答案 0 :(得分:0)

will_paginate使用当前网址创建网址并附加&#34; page&#34;到最后。

由于它来自于评论中使用的创建操作,因此将其作为起点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