在不删除会话的情况下获取当前用户的实际 ID? railswill_paginate进退两难

Get the actual id of current user without deleting the session? rails will_paginate dilema

由于 will_paginate 的 url 中存在问题,我想获取用户的真实 ID,因为我需要手动设置它,所以我想获取目标 link 因为将在视图中通过自定义渲染器方法分页,

<%= 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}" 是重要的一行,我需要在其中为 will_paginate 锚点 link 设置 url 和当前用户 ID。

问题是,当我在视图中使用的助手 运行 来设置 url 时,我得到一个错误 undefined local variable or method session...,您不能在助手中使用会话散列,所以如何获取 current_user 的真实 ID 以插入到变量中。我 delete/destroy 会话获取 ID 并创建一个新 ID 吗?问题是一旦我删除会话如何在删除会话和用户引用被删除后获取 ID。

原因 我有一个在 div 中呈现的 friends#index 操作,在初次调用 url 时,分页正确附加为 url users/:id/friends,因此每个分页请求都会转到正确的用户和操作。但是这个索引视图有 "Unfriend" 形式附加到每个显示的朋友,所以你可以破坏朋友控制器的销毁动作的友谊所以标记是例如 <form... action="friends/177"...> 并且在索引动作的全视图重新加载from destroy 操作将分页附加到最后一个已知的 link 除非被覆盖。因此,当索引操作再次完全呈现时,分页 links 是 friends/177 无论如何都会给出服务器错误并且没有任何意义,因为该记录刚刚被销毁。

我的销毁操作中有 current_user 变量和 ID,但我找不到将它们放入我的辅助方法的方法,或者只是从会话中获取当前用户 ID。

好的,感谢 max 和大家帮助我。找到了这个 post 和这个答案 here 你可以做类似的事情,

在你的路线中

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 操作返回并匹配例如 users/1/friends 通过 users/:user_id/friends 因为它在 routes.rb 中排在第一位。 here 在 rails 指南中解释了它是如何工作的。