2014-09-26 51 views
0

所以我想優化我的ActiveRecord查詢做更有效的事情。目前,當我查詢使用遵循我的方法得到類似如下:活動記錄查詢與用戶範圍

SELECT "expirations".* FROM "expirations" WHERE (user_id = 14 and expire_on <= '2014-09-25') 
SELECT "expirations".* FROM "expirations" WHERE (user_id = 15 and expire_on <= '2014-09-25') 
SELECT "expirations".* FROM "expirations" WHERE (user_id = 17 and expire_on <= '2014-09-25') 

等等,直到所有用戶的查詢完成。什麼會更有效率,我想要達到的是類似於以下內容:

SELECT "expirations".* FROM "expirations" WHERE (user_id IN (14,15,17) and expire_on <= '2014-09-25') 

有意義嗎?我不知道如何去做這件事,所以一些方向將是特殊的!

def expired_trainings(current_user) 
    retval = [] 
    Organization.appropriate_users(current_user).each do |user| 
     Expiration.where("user_id = #{user.id} and expire_on <= '#{Date.today}'").each do |expir| 
     retval << expir 
     end 
    end 
    ttypes = [] 
    if current_user.max_role.downcase == 'leader' 
     current_user.leading_groups.each do |g| 
     g.training_types.each do |tt| 
      ttypes << tt 
     end 
     end 
     ttypes.flatten.uniq! 
     retval.delete_if { |expir| !ttypes.include?(expir.training_type) } 
    end 
    retval.flatten 
    end 
+1

我不確定,但試試這個,如果它幫助'retval = [] user_ids = Organization.appropriate_users(current_user).map(&:user_id) retval << Expiration.where(:id => user_ids,: expire_on =>#{Date.today})' – Sontya 2014-09-26 04:47:31

+1

使用pluck代替映射'user_ids = Organization.appropriate_users(current_user).pluck(:user_id)' – Sontya 2014-09-26 05:22:58

回答

1

可以簡化(優化)此塊:

retval = [] 
Organization.appropriate_users(current_user).each do |user| 
    Expiration.where("user_id = #{user.id} and expire_on <= '#{Date.today}'").each do |expir| 
    retval << expir 
    end 
end 

下到這一點:

appropriate_users = Organization.appropriate_users(current_user) 
retval = Expiration.where(user_id: appropriate_users).where(['expire_on <= ?', Date.today]) 

這將在一個查詢中檢索所有的appropriate_users的到期時間。

+0

正是我一直在尋找的!謝謝! – noname 2014-09-26 22:33:46