我有一个视图,显示文章,相关评论和添加新评论的表单。使用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
<% 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 %>
答案 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