简体   繁体   English

Rails will_paginate链接不正确

[英]Rails will_paginate links incorrect

I have a view that displays an article, associated comments and a form to add a new comment. 我有一个显示文章,相关注释和添加新注释的表单的视图。 The list of comments is paginated using will_paginate with new comments added using ajax. 使用will_paginate对注释列表进行分页,并使用ajax添加新注释。

When the page is loaded the link is as follows: 加载页面后,链接如下:

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

When a new comment is added the comments#create action initialises the @comments variable and updates the pagination using ajax however the link created is incorrect: 添加新注释时,comment#create操作会初始化@comments变量并使用ajax更新分页,但是创建的链接不正确:

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

Articles controller 物品管制员

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

Comments controller 评论控制器

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 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 creates a URL using the current URL and appending "page" to the end of it. will_paginate使用当前URL创建一个URL,并在其末尾附加“页面”。

Since it is coming from the create action used on comments, it is given this as a starting point URL: 由于它来自用于注释的create动作,因此将其作为起点URL:

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

You can change this through using specific parameters, detailed here: https://github.com/mislav/will_paginate/wiki/API-documentation 您可以通过使用特定参数来更改此设置,在此处进行详细说明: https : //github.com/mislav/will_paginate/wiki/API-documentation

This should fix the problem: 这应该可以解决问题:

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

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

:params allows you to change the parameters used by the url_for method. :params允许您更改url_for方法使用的参数。 You can view information regarding url_for here: http://apidock.com/rails/ActionController/Base/url_for 您可以在此处查看有关url_for信息: http : //apidock.com/rails/ActionController/Base/url_for

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM