簡體   English   中英

帶有單表繼承N + 1問題的Rails MySQL查詢

[英]Rails MySQL query with Single Table Inheritance N+1 issue

我正在嘗試查找在給定時間內注冊了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關聯?

查看#has_manyAPI文檔 ,以查看具體實現,然后滾動到頂部的“關聯的快速加載 ”部分以查看一般概述。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM