[英]Issue with will_paginate page links
我目前有一个评论模型,在微博下发布,两者都显示在同一页面上。 问题是两者都显示在同一页面上,并且两者都是分页的,我试图用facebook方法进行微观测量。 以下是以下问题:
两个分页的链接变成这个href="/users/2?page=2"
而不是href="/users/2/micropost?page=2"
或者href="/users/2/comment?page=2"
。 我不确定如何解决这个问题。 这是我的一些代码。 所有建议都非常感谢!
Micropost渲染HTML
<table class="microposts">
<% if microposts.any? %>
<%= render microposts %>
<%= will_paginate microposts, :page_links => false %>
<% else %>
<div class="EmptyContainer"><span class='Empty'>Add a thread!</span></div>
<% end %>
</table>
评论部分HTML
<div id='CommentContainer-<%= micropost.id%>' class='CommentContainer Condensed2'>
<div class='Comment'>
<%= render :partial => "comments/form", :locals => { :micropost => micropost } %>
</div>
<div id='comments'>
<% comments = micropost.comments.paginate(:per_page => 5, :page => params[:page]) %>
<%= render comments %>
<%= will_paginate comments, :class =>"pagination" %>
</div>
</div>
显示页面的用户控制器
def show
@user = User.find(params[:id])
@comment = Comment.find(params[:id])
@micropost = Micropost.new
@comment = Comment.new
@comment = @micropost.comments.build(params[:comment])
@comments = @micropost.comments.paginate(:page => params[:page], :per_page => 5)
@microposts = @user.microposts.order('created_at DESC').paginate(:per_page => 10, :page => params[:page])
respond_to do |format|
format.html
format.js
end
end
问题在于为每个页面创建URL的will_paginate方式(它与jQuery没有任何关系)。
通过设计,will_paginate会尽力猜测页面用户的基本URL是什么(在内部它使用控制器/动作来做到这一点)。 然后将该基本URL与传递给will_paginate助手的任何额外参数组合使用:params
和succesive页码。
目前(will_paginate 3.0.3),为了覆盖此默认行为,您需要编写自定义LinkRenderer类。 下面是这样一个类的例子 - 它使用了新的额外选项:base_link_url
,可以传递给will_paginate视图助手。 然后,在创建分页链接时,将传递的字符串用作基础。 如果:base_link_url
未传递:base_link_url
选项,则它将回:base_link_url
默认行为。
将以下类放在某个地方,rails可以在加载时找到它(例如/ lib,只要你将/ lib添加到application.rb
的自动加载路径):
# custom_link_renderer.rb
class CustomLinkRenderer < WillPaginate::ActionView::LinkRenderer
def prepare(collection, options, template)
@base_link_url = options.delete :base_link_url
@base_link_url_has_qs = @base_link_url.index('?') != nil if @base_link_url
super
end
protected
def url(page)
if @base_link_url.blank?
super
else
@base_url_params ||= begin
merge_optional_params(default_url_params)
end
url_params = @base_url_params.dup
add_current_page_param(url_params, page)
query_s = []
url_params.each_pair {|key,val| query_s.push("#{key}=#{val}")}
if query_s.size > 0
@base_link_url+(@base_link_url_has_qs ? '&' : '?')+query_s.join('&')
else
@base_link_url
end
end
end
end
用法:
# in your view
will_paginate collection, :renderer => CustomLinkRenderer, :base_link_url => '/anything/you/want'
现在回到你的案子。 到这个时候你可能会看到解决方案 - 你可以在一个页面上有两个带有不同基本URL的will_paginate小部件,为这两个提供不同的:base_link_url
选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.