2013-05-07 63 views
0

我正在嘗試查找在給定時間段內註冊到ActionMovie計劃的所有用戶。我遇到了N + 1問題,並且花了很長時間纔得到新註冊數量。我想知道是否有任何創新的東西,我可以用arel_tables或類似的東西,可以幫助減少這個過程?任何建議表示讚賞!我當前的代碼看起來類似於下面:單表繼承N + 1問題的Rails mysql查詢

#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

您是否嘗試過預先加載使用:include選項Movie關聯?

看看在API docs#has_many看具體的落實和滾動到頂部到名爲協會的預先加載的部分看到一個概述。