具有一系列用户的活动记录查询

时间:2014-09-26 04:37:52

标签: ruby-on-rails ruby performance activerecord

所以我想优化我的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 个答案:

答案 0 :(得分: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的Expirations。