Ruby 嵌套数组迭代复杂度
Ruby nested array iterations complexity
我正在编写简单的 Rails 应用程序,我想获得一组由用户评分的书籍,但评分必须 > 0。现在我想知道我的查询的复杂性:
@ratedBooks = Book.all.select { |book| @user.ratings.select { |rate| rate.rate != 0 }.map { |rate| rate.book }.include? book }
是 n^2 还是 Ruby 正在评估每本书的内部数组?我可以做得更快吗?
你可以试试这个
Book.joins(:ratings).where('ratings.rate>0')
所以你得到所有评分高于 0 的书
是的,您的代码非常低效,因为它在应用程序中进行了所有过滤。您可以让数据库完成工作:
Rating.joins(:book).includes(:book)
.where(user: current_user)
.where('rate > 0')
.map(&:book)
要从用户评分的图书中检索所有评分,您可以使用:
@user.ratings.includes(:book).where("ratings.rate != ? and ratings.book_id", 0, book.id)
我正在编写简单的 Rails 应用程序,我想获得一组由用户评分的书籍,但评分必须 > 0。现在我想知道我的查询的复杂性:
@ratedBooks = Book.all.select { |book| @user.ratings.select { |rate| rate.rate != 0 }.map { |rate| rate.book }.include? book }
是 n^2 还是 Ruby 正在评估每本书的内部数组?我可以做得更快吗?
你可以试试这个
Book.joins(:ratings).where('ratings.rate>0')
所以你得到所有评分高于 0 的书
是的,您的代码非常低效,因为它在应用程序中进行了所有过滤。您可以让数据库完成工作:
Rating.joins(:book).includes(:book)
.where(user: current_user)
.where('rate > 0')
.map(&:book)
要从用户评分的图书中检索所有评分,您可以使用:
@user.ratings.includes(:book).where("ratings.rate != ? and ratings.book_id", 0, book.id)