gpt4 book ai didi

ruby-on-rails - rails : correct way of turning activerecord relation to array?

转载 作者:行者123 更新时间:2023-12-03 07:04:58 27 4
gpt4 key购买 nike

我试图使用 @videos.uniq{|p| 通过一个属性选择对象 uniq p.author}

  time = Time.new(2014, 12)
start_time = time.beginning_of_month
end_time = time.end_of_month

videos = Video.where("created_at > ? AND created_at < ?", start_time, end_time).where("likes > ?", 15)
selected_videos = videos.uniq{|p| p.author}
puts videos.count, videos.class, selected_videos.count
#=> 23, Video::ActiveRecord_Relation, 23

videos_first = videos.first(23)
selected_videos = videos_first.uniq{|p| p.author}
puts videos_first.count, videos_first.class, selected_videos.count
#=> 23, array, 10

.uniq 不适用于 ActiveRecord_Relation。问题是查询返回一个 Video::ActiveRecord_Relation,但我需要 array

当然,这可以通过使用to_a来实现,但是这样优雅吗?

  1. 处理这个问题的正确方法是什么?
  2. 是否可以将 .uniq 用于 activerecord:relation

最佳答案

如果需要访问查询结果,只需在 ActiveRecord::Relation 实例上使用#to_a即可。

rails guides您可以在 Rails 4.0 中发现显着的变化:“Model.all 现在返回一个 ActiveRecord::Relation,而不是一个记录数组。如果您确实想要一个数组,请使用 Relation#to_a。在某些特定情况下,这可能会导致损坏升级。”这对于其他关系方法(例如 :where)有效。

selected_videos = videos.to_a.uniq{|p| p.author}

关于ruby-on-rails - rails : correct way of turning activerecord relation to array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27791553/

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