[英]Rails 5 using will_paginate to create a load more button
So I'm trying to create a load more button (not infinite scroll although some simple js tweaks could make it so). 所以我试图创建一个更多的加载按钮(不是无限滚动,虽然一些简单的js调整可以使它如此)。 I'm using the will_paginate gem in Rails 5.
我在Rails 5中使用了will_paginate gem。
Its currently all working as expected except when I click load more it loads the next page posts twice eg: Load more > Post 4, Post 5, Post 6, Post 4, Post 5, Post 6 它目前全部按预期工作,除非我点击加载更多它加载下一页帖子两次,例如: 加载更多>帖子4,帖子5,帖子6,帖子4,帖子5,帖子6
FYI my 'posts' are @links: 仅供参考我的'帖子'是@links:
links_controller.erb links_controller.erb
def index
@links = Link.order('created_at DESC').paginate(:page => params[:page], :per_page => 3)
respond_to do |format|
format.html
format.js
end
end
views/links/index.html.erb 视图/链接/ index.html.erb
<div class="link-wrap">
<%= render @links %>
</div>
<% if @links.next_page %>
<div class="link more">
<%= link_to 'Load More', links_path(:page => @links.next_page), :class => 'next_page', :remote => true if @links.next_page %>
</div>
<% end %>
pagination.js.coffee pagination.js.coffee
$ ->
$('.next_page').on 'click', (e) ->
e.preventDefault()
url = $(this).attr('href')
$.getScript(url)
index.js.erb index.js.erb的
$('.link-wrap').append('<%= j render(@links) %>');
<% if @links.next_page %>
$('.next_page').attr('href','<%= links_path(:page => @links.next_page) %>');
<% else %>
$('.more').remove();
<% end %>
For the life of me I can't figure out why it would be rendering the links twice when 'load more' is clicked. 对于我的生活,我无法弄清楚为什么当点击“加载更多”时它会两次渲染链接。 This seems like a really simple thing but I'm struggling.
这似乎是一件非常简单的事情,但我正在努力。
If you check the server console, you can actually see two requests coming in, one triggered by your :remote => true
enabled link and other from your custom ajax. 如果您检查服务器控制台,您实际上可以看到两个请求进入,一个由您的
:remote => true
enabled链接触发,另一个来自您的自定义ajax。 Actually you don't need any js
to make this work. 实际上你不需要任何
js
来完成这项工作。 Just remove that click function from your pagination.js.coffee
or remove :remote => true
from the link. 只需从
pagination.js.coffee
删除该click函数,或从链接中删除:remote => true
。 After all both are doing the same thing. 毕竟两个人都在做同样的事情。 Hope this will help.
希望这会有所帮助。
So it was a stupid error of course. 所以这当然是一个愚蠢的错误。
Remove the line on index.html.erb: 删除index.html.erb上的行:
:remote => true if @links.next_page
So now it looks like this: 所以现在它看起来像这样:
<div class="link-wrap">
<%= render @links %>
</div>
<% if @links.next_page %>
<div class="link more">
<%= link_to 'Load More', links_path(:page => @links.next_page), :class => 'next_page' %>
</div>
<% end %>
All works fine now! 一切正常!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.