由于will_paginate的url中有问题,我希望获得用户的真实id,因为我需要手动设置它,所以我想通过视图中的自定义呈现器方法获得威尔分页的目标链接,
<%= will_paginate @friends, :renderer => WillPaginateHelper::MyLinkRenderer %>
帮手就像,
module WillPaginateHelper
class MyLinkRenderer < WillPaginate::ActionView::LinkRenderer
include SessionsHelper
protected
def link(text, target, attributes = {})
if target.is_a?(Integer)
attributes[:rel] = rel_value(target)
target = "/users" + current_user.id + "/friends?page=#{target}"
end
attributes[:href] = target
tag(:a, text, attributes)
end
end
end
行target = "/users" + current_user.id + "/friends?page=#{target}"
是我需要用当前用户id为will_paginate锚链接设置url的重要部分。
问题是,当我使用的帮助程序在视图中运行以设置url时,我得到一个错误undefined local variable or method session...
,您不能在帮助程序中使用会话散列,因此如何获取current_user的真实id以插入变量。我是否删除/销毁会话、获取id并创建一个新的id?问题是,一旦我删除会话,如何在删除会话和删除用户引用之后获得id。
原因I有一个在div中呈现的friends#index操作,在初始调用url时,分页正确地附加为url users/:id/friends
,因此每个分页请求都指向正确的用户和操作。但是这个索引视图在每个显示的朋友上都有“取消好友”的形式,这样你就可以破坏朋友控制器的破坏行为的友谊,所以标记是<form... action="friends/177"...>
,并且在全视图上,从破坏动作重新加载索引动作将分页附加到最后一个已知的链接上,除非被覆盖。因此,当索引操作再次被完全呈现时,分页链接就是friends/177
,它无论如何都会导致服务器错误,并且没有任何意义,因为该记录刚刚被销毁。
我在销毁操作中包含了current_user变量和id,但是我无法找到一种方法将它们获取到我的助手方法,或者简单地从会话中获取当前的用户id。
发布于 2017-11-11 05:14:58
好吧,谢谢麦克斯和大家的帮助。找到了这篇文章和答案这里,你可以这样做,
在你的路线上
get 'users/:cu_id/friends', to: 'users#index', as: :my_friends
也为观景
<%= will_paginate @friends, params: { controller: :users, :cu_id => current_user.id } %>
这会产生users/:cu_id/friends?page=2
..。当然,:cu_id将是实际的id号,用于分页。
编辑:如果您有任何其他路由到相同的url (例如,users/:user_id/friends
)嵌套资源,您需要在此下面放置get 'users/:cu_id/friends',...
,因为rails将为您构建正确的路径,因为分页时将通过friends#index操作返回,并且在routes.rb中第一个顺序匹配users/1/friends
(通过users/:user_id/friends
)。rails指南中的这里说明了它的工作原理。
https://stackoverflow.com/questions/47172647
复制相似问题