必须有比我的答案更好的方法,但是为什么不包括在内:user
,因为您在迭代查询时正在加载它们?
@user_list = Array.new
user_followers = UserFollow.includes(:user).where("user_1_id = ?", current_user.id)
# why did you include followers?
user_followers.each do |f|
@user_list << f.user
end
photos = Photo.includes(follow_relationships: { photo: :user }).where("user_id = ?", current_user.id)
photos.each do |p|
p.follow_relationships.each do |f|
@user_list << f.user unless @user_list.include? f.user
end
end
if @user_list.size < 150
users = User.where("verified = ? and first_name IS NOT NULL and last_name IS NOT NULL", true).limit(150 - @user_list.size)
# why did you include solutions?
users.each do |u|
@user_list << u unless @user_list.include? u
end
end
也许这更快,我不确定:
@follower_ids = UserFollow.where("user_1_id = ?", current_user.id).pluck(:user_1_id).uniq
@photo_ids = Photo.joins(follow_relationships: :photo)
@photo_ids = @photo_ids.where("user_id = ? and user_id not in (?)", current_user.id, @follower_ids)
@photo_ids = @photo_ids.pluck(:user_id).uniq
@followers = User.where("id in (?)", @follower_ids)
@photo_users = User.where("id in (?) and not in (?)", @photo_ids, @follower_ids)
@array_size = (@follower_ids + @photo_ids).size
if @array_size < 150
@users = User.where("verified = ? and first_name is not null and last_name is not null", true)
@users = @users.where("id not in (?)", @photo_ids + @follower_ids).limit(150 - @array_size)
else
@users = []
end
@final_array = @followers + @photo_users + @users
我还没有测试这是否有效,或者它是否更快。它有更多的数据库查询,但迭代次数更少。
更新
如果您向用户模型添加另一列,该列将更新为 1 到 3 的值,这取决于他们是否有关注者、照片或什么都没有。
那么你需要做的就是:
# in User model
def self.valid_users
where("verified = ? and first_name is not null and last_name is not null", true)
end
@users = User.valid_users.order("sortable ASC").limit(150)