简体   繁体   中英

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.

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:

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

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

Since it is coming from the create action used on comments, it is given this as a starting point 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

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. You can view information regarding url_for here: http://apidock.com/rails/ActionController/Base/url_for

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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