【问题标题】:method "where" does not work when switched from will_paginate to pagy gem in rails从 will_paginate 切换到 rails 中的 pagy gem 时,方法“where”不起作用
【发布时间】:2020-01-13 21:36:55
【问题描述】:

我在控制器中的 will_paginate 代码:

@posts = Post.paginate(page: params[:page], per_page: 100).order('created_at DESC')

替换它的我的页面代码:

@pagy, @posts = pagy_countless(Post.order('created_at DESC'), items:5, link_extra: 'class="" style="color:#222222; margin:3px;"')

我认为问题出在哪里:

<% @posts.where(user_id: current_user.friends).each do |post| %>

错误信息:

undefined method `where' for #<Array:0x00007f94329d1f70>
Did you mean?  when

我做错了什么?之前的 will_paginate 实现在显示用户朋友的所有帖子方面起作用。我不知道切换到 pagey 发生了什么变化。

更新:

所以目前,我通过将“where...”逻辑移动到控制器来解决这个问题。所以:

@pagy, @posts = pagy_countless(Post.where(user_id: current_user.friends).order('created_at DESC'), items:5, link_extra: 'class="" style="color:#222222; margin:3px;"')

现在它像以前一样工作了。但我仍然对为什么必须这样做感到困惑。

【问题讨论】:

    标签: ruby-on-rails ruby pagination will-paginate


    【解决方案1】:

    注意pagy_countless 返回一个项目数组,而不是 ActiveRecord 集合。这就是为什么你不能在 @posts 上使用 ActiveRecord 方法(比如 where)。

    按照我的链接查看使用to_a 将集合转换为数组,然后将其作为pagy_countless 的第二个参数返回:https://github.com/ddnexus/pagy/blob/bd88866ad6001ae1ef6ce63080d36ecff7bc5603/lib/pagy/extras/countless.rb#L29

    两个厘米:
    1. 在您的集合上调用pagy_countless 之前,您必须使用ActiveRecord 过滤器(例如:where 子句)
    2.如果需要在分页后过滤记录(这在大多数情况下没有意义),则必须使用Array方法,如rejectselect,如下@posts.select { |record| record.user.in?(current_user.friends) }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-29
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多