Rails:将activerecord关系转换为数组的正确方法?

cqc*_*991 42 activerecord ruby-on-rails

我试图用一个属性选择对象uniq @videos.uniq{|p| 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
Run Code Online (Sandbox Code Playgroud)

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

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

  1. 处理这个问题的正确方法是什么?
  2. 是可以使用.uniqactiverecord:relation

Ale*_*bio 47

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

rails指南中,您可以在Rails 4.0中找到值得注意的更改:"Model.all现在返回一个ActiveRecord :: Relation,而不是一个记录数组.如果您真的想要一个数组,请使用Relation#to_a.在某些特定情况下,这可能会升级时会导致破损." 这适用于其他关系方法,例如:where.

 selected_videos = videos.to_a.uniq{|p| p.author}
Run Code Online (Sandbox Code Playgroud)