[英]Rails 5.2 ActiveRecord query returns array instead of ActiveRecord::AssociationRelation
I see that performing a .first() or .last() query on an ActiveRecord query returns an array instead of an ActiveRecord::AssociationRelation. 我看到对ActiveRecord查询执行.first()或.last()查询返回的是数组,而不是ActiveRecord :: AssociationRelation。 This prevents me from appending an .order() clause as that is not an array method.
这可以防止我附加.order()子句,因为这不是数组方法。
Stepping back to the goal for a minute, I want to pull the latest five ("live", ie. active) comments related to a post and this is the code that fails: 回到目标上一分钟,我想提取与帖子相关的最新五个(“实时”,即活动)注释,这是失败的代码:
@post.comments.where(status: "live").last(5).order(id: :desc)
The error is 错误是
undefined method `order' for #<Array:0x00000011b096c0>
#<Array:0x00000011b096c0>的未定义方法`order'
If I remove the .last() clause, or the .order() clause I get a valid result but obviously not the result set that I am angling for. 如果删除.last()子句或.order()子句,我会得到有效结果,但显然不是我想要的结果集。
What's the best way to get the last five live comments in reverse chronological order? 按时间倒序获得最后五个实时评论的最佳方法是什么? More importantly, perhaps, where is the best documentation / tutorial on this syntax?
更重要的是,也许,关于此语法的最佳文档/教程在哪里? I find the official guide too brief.
我觉得官方指南太简短了。
Talking about documentation, I could recommend Rails API . 关于文档,我可以推荐Rails API 。 It has a lot of detailed descriptions for each interface method.
它对每种接口方法都有很多详细的说明。
What about your question, you could use limit
method instead of first
or last
: 你的问题是什么,你可以使用
limit
方法,而不是first
或last
:
@post.comments.where(status: "live").limit(5).order(id: :desc)
It does not affect the type of result (it stays ActiveRecord::AssociationRelation
). 它不影响结果的类型(它停留
ActiveRecord::AssociationRelation
)。 Hence, if no result is found, this relation with to_a
method will be converted to an empty array. 因此,如果未找到结果,则与
to_a
方法的关系将转换为空数组。 This is different from the behavior of first
and last
methods which return nil
in case of no result. 这是从行为不同的
first
和last
它会返回方法nil
在没有结果的情况下。
How about something like: 怎么样:
@post.comments.where(status: 'live').order(created_at: :desc).take(5)
I just plugged in created_at
. 我刚刚插入
created_at
。 Maybe you'll want updated_at
instead. 也许您会希望使用
updated_at
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.