[英]Rails MySQL query with Single Table Inheritance N+1 issue
I am trying to find all users that signed up during a given period of time to the ActionMovie plan. 我正在尝试查找在给定时间内注册了ActionMovie计划的所有用户。 I am running into an N+1 problem and it's taking me a very long time to get the number of new signups. 我遇到了N + 1问题,要花很多时间才能获得新的注册人数。 I was wondering if there was any creative thing I could do with arel_tables or something like that that could help cut down on this process? 我想知道我是否可以使用arel_tables或类似的东西来减少这个过程?
My current code looks similar to the below: 我当前的代码类似于以下内容:
#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
Have you tried eager loading the Movie
association using the :include
option? 您是否尝试过使用:include
选项渴望加载Movie
关联?
Take a look at the API docs for #has_many
to see specific implementation and scroll to the top to the section called Eager loading of associations to see a general overview. 查看#has_many
的API文档 ,以查看具体实现,然后滚动到顶部的“关联的快速加载 ”部分,以查看一般概述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.