gpt4 book ai didi

mysql - Rails MySQL 查询单表继承 N+1 问题

转载 作者:行者123 更新时间:2023-11-29 13:52:53 24 4
gpt4 key购买 nike

我正在尝试查找在给定时间段内注册 ActionMovie 计划的所有用户。我遇到了 N+1 问题,我花了很长时间才获得新注册的数量。我想知道是否可以使用 arel_tables 或类似的东西做一些有创意的事情来帮助减少这个过程?

我当前的代码类似于以下内容:

#find all UserMovies created during time frame
user_movies = UserMovie.where(:created_at => start_time..end_time)
#find users
users = user_movies.collect {|um| um.user}
#iterate through each users user_movies and see if the their first action movie was during the time frame I am looking for
users.each do |user|
user_movies_array = user.user_movies.map {|um| {um.movie.type => um.created_at}}
user_movies_array.each do |um|
if um["ActionMovie"] > start_time
puts "new user"
end
end
end


Class User
has_many :user_movies
has_many :movies, :through => :user_movies
end

Class Movie
has_many :user_movies, :foreign_key => :movie_id
has_many :users, :through => :user_movies
end

Class UserMovie
belongs_to :user
belongs_to :movie
end

Class ActionMovie < Movies
end

Class SuspenseMovie < Movies
end

最佳答案

您是否尝试过使用 :include 选项预先加载 Movie 关联?

看看API docs #has_many 查看具体实现,并滚动到顶部名为关联的预加载的部分以查看总体概述。

关于mysql - Rails MySQL 查询单表继承 N+1 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16419410/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com