过滤 Rails 中看不见的视频的最佳方式

Best way to filter unseen videos in Rails

我们为我们的用户建立了一个视频部分。用户可以按 rating/views/date 过滤视频。 用户也可以决定隐藏已经看过的视频。这是我有点挣扎的地方。

现在我有一个解决方案,它正在运行,但似乎表现不佳。

if @filter == "newest"
  if @unseen
    ids = Videothek::Video.where(videothek_category_id: categories).pluck(:id)
    views = Videothek::Video::View.where(user_id: current_user.id).pluck(:video_id)
    unseen = ids - views #ids der ungesehenen videos
    @videos = Videothek::Video.where(id: unseen).order("created_at DESC")
  else
    @videos = Videothek::Video.where(videothek_category_id: categories).order("created_at DESC")
  end
end

我认为一定可以使用范围,例如 Videothek::Video.unseen(current_user).order(.....)

A Video has_many Views,但我很难加入 运行,因为我只想要视频,不要与 [= =30=],其中 user_id = 1(或 current_user.id)。

有人可以帮我吗?

顺便说一句:我们在 RoR3

您可以使用where.not(video_id: [ids]) 使数据库过滤用户已经看过的视频。这个方法是从rails 4.

开始添加的

https://robots.thoughtbot.com/activerecords-wherenot

您可以使用 .ids 而不是 pluck(:id)。我还会将代码移出控制器。

您的问题可能更适合 https://codereview.stackexchange.com/,因为您已经有了工作版本。