mysqlruby-on-railsrubyactiverecordsti

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. I am running into an N+1 problem and it's taking me a very long time to get the number of new signups. 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?

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

Solution

  • Have you tried eager loading the Movie association using the :include option?

    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.