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

时间:2013-05-07 12:44:35

标签: mysql ruby-on-rails ruby activerecord sti

我正在尝试查找在给定时间段内注册到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

1 个答案:

答案 0 :(得分:1)

您是否尝试使用Movie选项急切加载:include关联?

查看#has_many {{1}}以查看具体实施情况,并滚动到顶部的急切加载关联一节,以查看概述。< / p>