我有一个查询,可以获取所有图像并过滤当前的用户上传,额定和喜欢的图像。但这消耗了更多的时间。请参阅下面的查询,并提出最佳查询以减少执行时间。
@images = Image.active_images.order('images_order')
.where.not(user_id: current_user.id)
.select{|item| item.ratings.where(user_id: current_user.id).count <= 0 }
.select{|item| item.favorite_images.where(user_id: current_user.id).count <= 0 }
您可以从n 1查询开始。请参阅http://guides.rubyonrails.org/active_record_querying.html。
您使用的预加载关联将大大减少您的执行时间。
更大的提升是通过使用Arel或Pure SQL在一个查询中完成所有这些。
可能的解决方案:
Image.active_images.joins(:ratings, :favorite_images)
.where.not(user_id: current_user.id)
.where.not(ratings: { user_id: current_user.id})
.where.not(favorite_images: { user_id: current_user.id })
.distinct #Joining has_many associations might duplicate the image records in your select, so use distinct
.order(:images_order)