【问题标题】:complex query to load records from multiple nested records从多个嵌套记录中加载记录的复杂查询
【发布时间】:2015-01-02 08:26:24
【问题描述】:

我有一个用户模型

class User < ActiveRecord::Base
  has_many :watched_videos
  has_and_belongs_to :course
end

和课程模型

class Course < ActiveRecord::Base
  has_many :videos      
  has_and_belongs_to :users
end

还有一个视频模型

class Video < ActiveRecord::Base
  belongs_to :course
  has_many :watched_videos      
end

我的 wathed 视频模型看起来像

class WatchedVideo < ActiveRecord::Base
  belongs_to :user
  belongs_to :video      
end

我想要用户观看过所有视频的所有课程。例如。有两门课程,每门课程有 2 个视频,用户已经看过课程一的所有视频,我的查询必须返回该课程。我该如何实现?

【问题讨论】:

    标签: mysql ruby-on-rails activerecord


    【解决方案1】:

    首先获取所有观看过任何视频的用户:

    users = WatchedVideo.pluck('Distinct("user_id")')
    

    获取所有具有以上用户的课程:

    courses = Course.includes(:videos).where('user_id in (?)', users)
    

    遍历课程以查找观看了所有视频的课程:

    cour = []
    courses.each do |c|
     c.users.each do |u|
      cour << c if u.wathced_videos.pluck(:video_id) == c.videos.pluck(:id)
     end
    end
    

    还有优化的余地。你可以进一步优化这个

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-10
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-13
      相关资源
      最近更新 更多