簡體   English   中英

Rails的ActiveRecord的5.2查詢返回數組,而不是ActiveRecord的:: AssociationRelation

[英]Rails 5.2 ActiveRecord query returns array instead of ActiveRecord::AssociationRelation

我看到對ActiveRecord查詢執行.first()或.last()查詢返回的是數組,而不是ActiveRecord :: AssociationRelation。 這可以防止我附加.order()子句,因為這不是數組方法。

回到目標上一分鍾,我想提取與帖子相關的最新五個(“實時”,即活動)注釋,這是失敗的代碼:

@post.comments.where(status: "live").last(5).order(id: :desc)

錯誤是

#<Array:0x00000011b096c0>的未定義方法`order'

如果刪除.last()子句或.order()子句,我會得到有效結果,但顯然不是我想要的結果集。

按時間倒序獲得最后五個實時評論的最佳方法是什么? 更重要的是,也許,關於此語法的最佳文檔/教程在哪里? 我覺得官方指南太簡短了。

關於文檔,我可以推薦Rails API 它對每種接口方法都有很多詳細的說明。

你的問題是什么,你可以使用limit方法,而不是firstlast

@post.comments.where(status: "live").limit(5).order(id: :desc)

它不影響結果的類型(它停留ActiveRecord::AssociationRelation )。 因此,如果未找到結果,則與to_a方法的關系將轉換為空數組。 這是從行為不同的firstlast它會返回方法nil在沒有結果的情況下。

怎么樣:

@post.comments.where(status: 'live').order(created_at: :desc).take(5)

我剛剛插入created_at 也許您會希望使用updated_at

暫無
暫無

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

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