gpt4 book ai didi

ruby-on-rails - rails : get the first n active record objects of a model

转载 作者:数据小太阳 更新时间:2023-10-29 07:55:05 26 4
gpt4 key购买 nike

我需要一种方法来获取模型的前 n 项。 Item.first(n)Item.all[1..n] 会这样做,只是它们返回的是数组,而不是对象。如何将其作为 ActiveRecord 对象获取?

irb(main):135:0> Player.where(game_id: 1).class
=> Player::ActiveRecord_Relation #Ok
irb(main):136:0> Game.first.players.class
=> Player::ActiveRecord_Associations_CollectionProxy #Ok
irb(main):137:0> Player.where(game_id: 1).first(2).class
=> Array #Not Ok

我想对返回的玩家集合运行 update_all,但我不能对数组执行此操作。

最佳答案

你做 .limit(n)

将它与 .offset 结合起来,你就有了分页。

关于ruby-on-rails - rails : get the first n active record objects of a model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41470951/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com