簡體   English   中英

當從 will_paginate 切換到 rails 中的 pagy gem 時,方法“where”不起作用

[英]method "where" does not work when switched from will_paginate to pagy gem in rails

我在控制器中的 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 實現在顯示用戶朋友的所有帖子方面起作用。 我不知道在切換到 pag 時發生了什么變化。

更新:

所以目前,我已經通過將“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;"')

現在它像以前一樣工作。 但我仍然很困惑為什么我必須這樣做。

請注意pagy_countless返回一個項目數組,而不是一個 ActiveRecord 集合。 這就是為什么你不能在@posts上使用 ActiveRecord 方法(比如where )。

按照我的鏈接查看使用to_a將集合轉換為數組,然后將其作為pagy_countless第二個參數返回: https : //github.com/ddnexus/pagy/blob/bd88866ad6001ae1ef6ce63080d36ecff7bc5603/lib/pagy/extras/countless# L29

兩條評論:
1. 在對集合調用pagy_countless之前必須使用 ActiveRecord 過濾器(例如: where子句)
2.如果你需要在分頁后過濾記錄(這在大多數情況下沒有意義),你必須使用像select of reject這樣的Array方法,如下@posts.select { |record| record.user.in?(current_user.friends) } @posts.select { |record| record.user.in?(current_user.friends) }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM